Why doesn’t the button respond when I set onPressed in onLoad?
The settings for position and the button itself (in this case, a TextComponent) are working, but for some reason, the function set for onPressed is not being called.
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame/particles.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const FooApp());
}
class FooApp extends StatelessWidget {
const FooApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: GameWidget.controlled(gameFactory: TextGame.new),
);
}
}
class TextGame extends FlameGame {
@override
Future<void> onLoad() async {
super.onLoad();
await add(
BButton(),
);
}
}
class BButton extends ButtonComponent {
@override
Future<void> onLoad() async {
super.onLoad();
position = Vector2(size.x * 0.5, size.y * 0.5);
onPressed = () { // NOT WORK
print("Test");
};
button = TextComponent(
text: 'B',
textRenderer: TextPaint(
style: const TextStyle(
fontSize: 88,
color: Colors.white,
),
),
);
}
}
Since I can’t inherit from ButtonComponent, I’m using it without inheritance.
2
Answers
Try these:
It is because you haven’t set a
size
of the button, so it will never "contain" the tap position.This should work: