Search code examples
flutterflame

Flame onLoad vs constructor initialization


If I create a component in Flame like this:

class MyComponent extends PositionComponent {
  MyComponent() {
    // Option 1
  }

  @override
  Future<void> onLoad() {
    // Option 2
  }
}

What difference does it make if I initialize my component in the constructor (Option 1) or the onLoad method (Option 2)?


Solution

  • If you have things that need to load before the component is added to the game, like an image for example, then you need to do that loading in onLoad so that the game knows that it shouldn't add your component to the game until everything in there is loaded. For example:

    class MyComponent extends PositionComponent {
      @override
      Future<void> onLoad() async {
        final sprite = await loadSprite('flame.png');
      }
    }
    

    So to make your code consistent you can do all your initialization in onLoad, even if it is not needed for all your components.

    Another good thing to know about onLoad is that if your are using the HasGameRef mixin the gameRef will be set to your component in onLoad, but not in the constructor.