Search code examples
flame

how to use RouterComponent, if I want to save some State


here is my Character class:

class Character extends Component {
  bool isMoving = false;
  ...
}

here is for instance Forge2DGame class:

class MainGame extends Forge2DGame {
...
  Character character; //<-- here I thought I can create an instance and get the value later for other class
  @override
  Future<void> onLoad() async {
    add(
      router = RouterComponent(
        initialRoute: 'character',
        routes: {
          'character': Route(character), //<-- here is my question
        },
      ),
    );
 }
}

and now I want to get character movement Data for Scene class, like this?

class Scene extends Component with HasGameRef<MainGame> {
  ...
  bool characterMovement = gameRef.character.isMoving; 
}

So my questions is:

  1. if I use like tutorial showed Route(Character.new), does it mean, everytime there will be a new instance, so the Scene class can not get the value from instantiated character?Or how to achieve my expectation?

  2. I got the error:

    This requires the 'constructor-tearoffs' language feature to be enabled. Try updating your pubspec.yaml to set the minimum SDK constraint to 2.15.0 or higher, and running 'pub get'.

Since I am using sdk: ">=2.11.0 <3.0.0" (I didnt want to use null safety for now), can I still use RouterComponent?

Thanks!

===========================UPDATE===========================

hi Spydon, thanks for the reply, Can I use RouterComponent like this? So I can get the same value from instantiated character, or what is the right solution, I think I didnt find a reference from docs.

class MainGame extends Forge2DGame {
...
  Character character;
  @override
  Future<void> onLoad() async {
    add(
      router = RouterComponent(
        initialRoute: 'character',
        routes: {
          'character': Route( () => character), 
        },
      ),
    );
 }
}

Solution

    1. It will only instantiate a new instance every time if you send in maintainState = false to the Route constructor.

    2. If you can't use a higher SDK (which I highly recommend since Dart 3 will make nullsafety mandatory) or if you don't want to use constructor tear-offs you just have to create a lamda that creates the object, this is the same thing:

    Route(() => Character());