Search code examples
flutterdartflame

How to navigate to widgets outside of a Flutter Flame Engine game widget


Is it possible to navigate out of a Flame Engine game widget into other Flutter widgets?

The app below immediately loads the game widget. How can navigation outside of the Game widget to another Flutter widget be achieved?

Flutter version: 2.2.3
Dart version: 2.13.4
Flame Engine version: flame-1.0.0-rc8

main.dart

import 'package:flame/flame.dart';
import 'package:flame/game.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:my_game.dart';

void main() {
  runApp(
    GameWidget(
      game: MyGame(),
    ),
  );
}

my_game.dart

import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame/gestures.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class MyGame extends BaseGame with TapDetector {
    @override
    void update(double dt) { /* TODO */ }

    @override
    void render(Canvas canvas) { /* TODO */ }

    @override
    void onTapUp(TapUpDetails details) {
        // How to navigate outside of the game widget?
    }
}

Solution

  • You can do two things:

    • Either put the GameWidget in a Stack and handle navigation by Navigator from Flutter and remove and add the GameWidget to the widget tree when deemed necessary. Flutter Navigation docs
    • Use the Overlays API in Flame to handle the state from within Flame instead. Flame docs

    For using the overlays you add the overlays that you want to have accessible when you create the GameWidget and then you call game.overlays.add to render a specific widget, and game.overlays.remove to stop rendering it.

    I do recommend that you upgrade from rc8 to rc13, since the docs are for that version and things are more stable in general.