Sub topic 8
`late` and `late final`: Deferred and Lazy Initialization
This chapter assumes you know Dart variables, classes, constructors, and nullable types such as String?. It focuses on cases where a non-nullable value cannot be initialized at the declaration site.
Why use `late`?
Dart requires every non-nullable variable to have a value before it is read. This rule catches uninitialized-value bugs at compile time when possible.
Sometimes initialization must happen later. For example, a Flutter widget may receive a value during setup, or an object may need to perform work only when a value is first requested. The late modifier tells Dart:
- This variable is non-nullable.
- It will be initialized before its first read.
- The compiler should allow its declaration without an immediate value.
If the variable is read before it is initialized, Dart throws a LateInitializationError at runtime.
class Session {
late String userId;
void start(String id) {
userId = id;
}
void printUser() {
print(userId);
}
}
void main() {
final session = Session();
session.start('user-42');
session.printUser(); // user-42
}userId is not nullable. After start assigns it, code can use it as a normal String.
A nullable field expresses a different meaning. String? userId says that “no value” is a valid state. late String userId says that a value is required, but its assignment is deferred.
`late final`: assign once
Use late final when a value must be assigned later but must not change afterward. This is useful for values established during setup.
class Configuration {
late final String environment;
void load(String value) {
environment = value;
}
}
void main() {
final config = Configuration();
config.load('production');
print(config.environment);
// config.environment = 'test';
// Compile-time error: a final variable can be assigned only once.
}The first assignment to a late final field is allowed after construction. A second assignment is an error. This gives the field a lifecycle of “uninitialized, then fixed.”
Lazy initialization
A late variable can have an initializer. In that form, Dart delays the initializer until the first read. This is called lazy initialization. The result is then stored and reused.
class Report {
late final String text = _build();
String _build() {
print('building report');
return 'Monthly report';
}
}
void main() {
final report = Report();
print('created');
print(report.text);
print(report.text);
}The output is:
created
building report
Monthly report
Monthly reportThe _build method runs only when text is first read. Because the field is late final, the generated value is cached and cannot be replaced.
Lazy initialization is useful when the value is expensive and may never be needed. It can also make construction cheaper. The trade-off is that failures move from construction time to the first read, so the access point must be prepared for that possibility.
Initialization flow
The following flow shows the two common forms of late.
Common errors
A deferred field must be assigned on every path that can lead to a read.
class UserProfile {
late final String displayName;
void load({required bool found}) {
if (found) {
displayName = 'Ada';
}
}
String name() => displayName;
}
void main() {
final profile = UserProfile();
profile.load(found: false);
// Throws LateInitializationError.
print(profile.name());
}Prefer a required constructor parameter when the object cannot be valid without the value:
class UserProfile {
final String displayName;
UserProfile({required this.displayName});
}Use late when construction and initialization genuinely happen in separate stages, or when lazy work is valuable. Do not use it merely to silence an initialization error.
Exercise
When should you choose late final String value = build() instead of String? value?
Show answer
Choose late final when a non-null value is required eventually, the value can be computed later, and it must not change after initialization. Choose String? when the absence of a value is a valid state.