'Why I get Bad state: Cannot find reference SomeGame in the component tree in Flutter Flame?

I want to reset game to its initial state and removing all the components in a method. After resetting I get this error:

Bad state: Cannot find reference TurtleGame in the component tree

It seems the gameRef doesn't loaded already even if I have HasGameRef mixin in the signature of the class. Why gameRef has reference to the game when first time the game starts and the player component works correctly! but after resetting gameRef reference is missing?



Solution 1:[1]

You can only access gameRef as long as the Component is mounted in the component tree. So you can't access it in the constructor for example, or after the component has been removed (until it is fully added to the tree again).

Override onLoad if you need to access it the first time the component is loaded and override onMount if you need to access it every time that the component is added to the component tree.

class YourComponent extends Component with HasGameRef<MyGame> {
  @override
  Future<void> onLoad() {
    // Only runs once, when the component is loaded.
    print(gameRef.size.y);
  }

  @override
  void onMount() {
    // Runs every time that the component is added to the component tree.
    print(gameRef.size.y);
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 spydon