If you've been working with Flutter for a while you probably have something like the next snippet somewhere in your code
class _MyWidgetState extends State<MyWidget>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
_controller = AnimationController(vsync: this);
}
}
But did you know that you can:
late x;
//...
x = 'something';
x = 'something else';
I sure didn't. Somehow I was sure that it was the same as marking the member as `final`. So if you were surprised by this incredible discovery, here's what you should be doing:
late final x;
//...
x = 'something';
x = 'something else'; // this is now an error, enforced by the analyzer
There is another interesting interaction with `late`. Lazy initialization.
If, for any reason, a member is expensive to initialize and you rather do that operation only when and if it is first accessed. You can use:
late final x = SomeExpensiveClass();
And get this. Because this is called after the parent class was initialized, you can call on members of the parent class (and even methods)
late final x = SomeExpensiveClass(this.otherField);
Though I still can't find a good "every day" example for the lazy init in Flutter, so if someone has a good one to share with me, let me know.
Comments