在onLoad中设置onPressed后ButtonComponent无响应的问题
核心原因
你的TextGame类没有混入HasTappables,Flame默认不会将触摸事件分发给可点击组件,导致按钮无法接收点击信号。
修改步骤
- 给
TextGame添加HasTappables混入,让游戏能处理触摸事件:
class TextGame extends FlameGame with HasTappables { @override Future<void> onLoad() async { super.onLoad(); await add( BButton(), ); } }
- 优化按钮位置设置(避免尺寸未初始化的问题):
当前代码中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
相关产品推荐
相关产品推荐

