In my previous article on sound null safety of Flutter and Dart, I simply forgot to discuss another keyword “late”.
Better late than never. 🙂
In the lib folder of my Dart console application, I have this code.
class Name {
late String _name;
String get getName => _name;
set setName(String aValue) => _name = aValue;
}
And in the bin folder in main dart file I instantiate the Name object this way:
var name = Name();
name.setName = 'Sanjib';
print(name.getName);
As expected, it gives the expected output : Sanjib.
However, what does that line mean?
late String _name;
It means, the Dart compiler keeps its faith on us that, we’ll never allow this private property to be null.
Is that real?
Oh, yes.
If we had assigned a null value, instead of assigning a String, it would give us an error.
Because, the compiler enforces that the value should be non-nullable.
In Flutter, the “late” keyword has other advantages though.
We’ll discuss that in the next article.
Leave a Reply