Dart late
Dart late Variables
A variable that is declared outside main() is called a top-level variable.
A non-nullable top-level variable must get a value at once, where it is declared.
If it does not, the program does not run:
Result:
main.dart:1:8: Error: Field 'city' should be initialized because its type 'String' doesn't allow null.
String city;
^^^^
The late keyword tells Dart: "This variable will get a value later, before it is used."
Result:
Oslo
The variable is still non-nullable, so you do not need ? or null checks.
LateInitializationError
With late, you make a promise to Dart.
Dart checks the promise when the program runs.
If you read a late variable before it has a value, the program stops with a LateInitializationError:
Result:
Unhandled exception:
LateInitializationError: Field 'city' has not been initialized.
Note: Only use late when you are sure that the variable gets a value before it is read.
late final
A late final variable gets its value later, but only one time.
Example
late final int highScore;
void main() {
highScore = 120;
print(highScore);
}
Try it Yourself »
Result:
120
If you try to give it a second value, the program stops with an error:
Example
late final int highScore;
void main() {
highScore = 120;
print(highScore);
highScore = 150;
}
Try it Yourself »
Result:
120
Unhandled exception:
LateInitializationError: Field 'highScore' has already been initialized.
Lazy Initialization
A late variable can also have a value in its declaration.
Then the value is not created at once.
It is created the first time the variable is read.
This is called lazy initialization.
In this example, loadMessage() is a small function that prints a line and returns a string (you will learn about functions in the Functions chapter):
Example
String loadMessage() {
print('Loading message...');
return 'Welcome!';
}
void main() {
late final String message = loadMessage();
print('Program started');
print(message);
print(message);
}
Try it Yourself »
Result:
Program started
Loading message...
Welcome!
Welcome!
"Program started" is printed first, because the message is not loaded until it is needed.
"Loading message..." is printed only once, because the value is kept after the first read.
If the variable is never read, the value is never created:
Example
String loadMessage() {
print('Loading message...');
return 'Welcome!';
}
void main() {
late final String message = loadMessage();
print('The message was not needed');
}
Try it Yourself »
Result:
The message was not needed
Tip: Lazy initialization is useful when a value is slow to create and you might not need it.