add method

FutureOr<void> add(
  1. Component component
)

Schedules component to be added as a child to this component.

This method is robust towards being called from any place in the user code: you can call it while iterating over the component tree, during mounting or async loading, when the Game object is already loaded or not.

The cost of this flexibility is that the component won't be added right away. Instead, it will be placed into a queue, and then added later, after it has finished loading, but no sooner than on the next game tick. You can await FlameGame.lifecycleEventsProcessed like so:

world.add(coin);
await game.lifecycleEventsProcessed;
// The coin is now guaranteed to be added.

When multiple children are scheduled to be added to the same parent, we start loading all of them as soon as possible. Nevertheless, the children will end up being added to the parent in exactly the same order as they were originally scheduled by the user, regardless of how fast or slow each of them loads.

A component can be added to a parent which may not be mounted to the game tree yet. In such case, the component will start loading immediately, but its mounting will be delayed until such time when the parent becomes mounted.

This method returns a future that completes when the component is done loading, and mounting if the parent is currently mounted. However, this future will not guarantee that the component will become "fully mounted": it still needs to be added to the parent's children list, and that operation will only be done on the next game tick.

A component can only be added to one parent at a time. It is an error to try to add it to multiple parents, or even to the same parent multiple times. If you need to change the parent of a component, use the parent setter.

Implementation

FutureOr<void> add(Component component) => _addChild(component);