onLoad method
Late initialization method for Component.
Usually, this method is the main place where you initialize your component. This has several advantages over the traditional constructor:
- this method can be
async; - it is invoked when the size of the game canvas is already known.
If your loading logic requires knowing the size of the game canvas, then
add HasGameReference mixin and then query game.size or
game.canvasSize.
The default implementation returns null, indicating that there is no
need to await anything. When overriding this method, you have a choice
whether to create a regular or async function.
If you need an asynchronous onLoad, make your override return
non-nullable Future<void>:
@override
Future<void> onLoad() async {
// your code here
}
Alternatively, if your onLoad function doesn't use any awaiting, then
you can declare it as a regular method returning void:
@override
void onLoad() {
// your code here
}
The engine ensures that this method will be called exactly once during
the lifetime of the Component object. Do not call this method manually.
Implementation
@override
Future<void> onLoad() async {
super.onLoad();
// Set the width of the list, using the provided width or the current size.
size.x = _width ?? size.x;
// Calculate the total height of the list, including spacing.
final totalHeight =
childrenComponents.length * childHeight +
(childrenComponents.length - 1) * spacing;
size.y = totalHeight;
// Arrange each child component in the vertical list.
for (int i = 0; i < childrenComponents.length; i++) {
final child = childrenComponents[i];
final y = i * (childHeight + spacing);
// Set the position and size of the child component.
child.position = Vector2(0, y);
child.size = Vector2(size.x, childHeight);
// Add the child component to the list.
add(child);
}
}