I met an error after flame updated to 1.4, here is the code:
class Ball extends BodyComponent {
...
Vector2 get position =>
//camera.worldToScreen(body?.position ?? Vector2.zero());
body?.position ?? Vector2.zero(); // <-error: flame Field 'body' has not been initialized
...
}
I noticed that from 1.0 to 1.4 Body added a late in the package and could be initialized through createBody(), but why body?.position ?? Vector2.zero()
does not work as i know the real-time position of the ball? thank you!
CodePudding user response:
When a field has the late
keyword it does not mean that the value can be null, which is what you are checking with the ?.
and ??
, late
means that you promise the runtime that the field will be initialized before it is used.
createBody
initializes the body
and only after that has run the BodyComponent
can be properly used. createBody
runs automatically in onLoad
, which is why it is important to call super.onLoad
the first thing you do if you override onLoad
.