With the introduction of NNBD in Dart 2.12, a new keyword was created: late. The primary reason this was created was to allow for non-null fields, that did not have to be immediately initialized.

// Allow this to be null for now, compiler trusts us, that we will assign it.
late final int i; 
MyConstructor(){
   i = getStartIndex(); // Compiler checks at this point, everything is ok!
   i = null; // This will cause an error, compiler is enforcing non-null
}

This was a necessary feature/workaround for Flutter, because of darts requirement to use const initializers, and most Flutter developers are likely familiar with it by now. In this post we’re going to look at some of the other benefits of late!

Lets get lazy…

late has another great application for your Flutter code: you can remove many of your initState/constructor calls!

This is because late runs “lazily”, which means it is not run at all until it is referenced the first time. This might sound un-important, but it has implications that are quite nice for general use cases: your field initializers code can access other fields, _methods _and ._this_!

This totally unlocks your initializer code to be more flexible. Typically you can not access other fields, or methods on the class instance:

However, when using late, these all work fine!

#code #flutter #source code

Flutter: Lazy instantiation with The `late` Keyword
33.85 GEEK