flutterdartflame

Difference Between HasGameReference and findGame in Flame


I found that both HasGameReference and findGame() are used in the example provided in the Flame documentation example code: https://github.com/flame-engine/flame/blob/main/doc/flame/examples/lib/router.dart

Here are the details:

StartPage:

class StartPage extends Component with HasGameReference<RouterGame> { 👈👈👈
  StartPage() {
    addAll([
      _logo = TextComponent(
        text: 'Your Game',
        textRenderer: TextPaint(
          style: const TextStyle(
            fontSize: 64,
            color: Color(0xFFC8FFF5),
            fontWeight: FontWeight.w800,
          ),
        ),
        anchor: Anchor.center,
      ),
      _button1 = RoundedButton(
        text: 'Level 1',
        action: () => game.router.pushNamed('level1'),  👈👈👈
        color: const Color(0xffadde6c),
        borderColor: const Color(0xffedffab),
      ),
...

PausePage

class PausePage extends Component
    with TapCallbacks, HasGameReference<RouterGame> { 👈👈👈
  @override
  Future<void> onLoad() async {
    final game = findGame()!; 👈👈👈
    addAll([
...

Solution

  • The HasGameReference mixin is just a cached version of findGame and is slightly more convenient to use since it exposes the game variable in the component, but you can use whichever you'd like.