You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在onLoad中设置onPressed后ButtonComponent无响应的问题

问题解决:ButtonComponent的onPressed无响应

核心原因

你的TextGame类没有混入HasTappables,Flame默认不会将触摸事件分发给可点击组件,导致按钮无法接收点击信号。

修改步骤

  1. 给TextGame添加HasTappables混入,让游戏能处理触摸事件:
class TextGame extends FlameGame with HasTappables {
  @override
  Future<void> onLoad() async {
    super.onLoad();

    await add(
      BButton(),
    );
  }
}
  1. 优化按钮位置设置(避免尺寸未初始化的问题):
    当前代码中position = Vector2(size.x * 0.5, size.y * 0.5)的size是BButton自身尺寸,此时还未赋值button,size可能为默认的Vector2.zero(),导致位置异常。可以改为设置锚点并基于游戏尺寸居中:
class BButton extends ButtonComponent {
  @override
  Future<void> onLoad() async {
    super.onLoad();

    anchor = Anchor.center; // 设置锚点为组件中心
    button = TextComponent(
      text: 'B',
      textRenderer: TextPaint(
        style: const TextStyle(
          fontSize: 88,
          color: Colors.white,
        ),
      ),
    );
    onPressed = () {
      print("Test");
    };
    // 基于游戏画布尺寸居中按钮
    position = Vector2(game.size.x * 0.5, game.size.y * 0.5);
  }
}

验证效果

重新运行代码后,点击按钮就能在控制台看到Test输出了。

内容的提问来源于stack exchange,提问作者shingo.nakanishi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 15:54:59