Sub topic 8
late and late final: deferred and lazy initialization
This chapter assumes you know basic Dart syntax, how classes and constructors work, and the difference between T and T?. It also assumes you have seen the rule that a non-nullable field must have a value before the constructor body runs.
The problem late solves
A non-nullable field needs a value before anyone can read it. Usually you meet that rule with a required parameter or an initializer list. Sometimes the value is not available at construction time. It may depend on other fields, cost too much to compute up front, or only exist after a framework calls a setup method.
The usual workaround is to make the field nullable and then check it everywhere. That makes every caller handle a state that is only temporary. The late modifier lets you keep the non-nullable type and tell the compiler: "I will initialize this before it is read."
late gives you two related features:
- Deferred initialization: a
latevariable with no initializer. You assign it later. - Lazy initialization: a
latevariable with an initializer. The initializer runs on the first read, not at construction.
Deferred initialization
Declare the variable without a value and assign it when the data becomes available.
class Session {
late String token;
void login() {
token = 'abc123';
}
}
void main() {
final s = Session();
try {
print(s.token);
} on LateInitializationError {
print('token read too early');
}
s.login();
print(s.token); // abc123
}The compiler does not check the order of the calls. If you read token before login() runs, Dart throws a LateInitializationError at run time. You have moved a compile-time guarantee to a run-time check, and the burden of getting the order right falls on you.
Lazy initialization
Add an initializer and the variable is computed the first time it is read.
class Report {
late final String text = _build();
String _build() {
print('building');
return 'report';
}
}
void main() {
final r = Report();
print('created');
print(r.text); // building, then report
print(r.text); // report only; the value is cached
}Output order is created, building, report, report. Constructing a Report is cheap, and the cost is paid only by code that reads text. If nothing reads it, the initializer never runs.
Access to this
A normal field initializer cannot refer to this or to other instance members, because the object is not fully built yet. A late initializer runs after construction, so it can use them.
class Config {
final String env;
late final String url = 'https://$env.example.com';
Config(this.env);
}
void main() {
print(Config('staging').url); // https://staging.example.com
}Without late, the declaration of url would be a compile-time error. You could write the same thing with an initializer list or a getter, but late final caches the result and keeps the declaration next to the field.
late final: assign once
Adding final limits the variable to a single assignment. The behavior depends on whether an initializer is present.
- With an initializer:
late finalhas no setter. You cannot assign to it at all, and the value is computed once on first read. - Without an initializer: you assign it exactly once, at any time. A second assignment throws
LateInitializationError.
class Job {
late final DateTime startedAt;
void start() {
startedAt = DateTime.now();
}
}
void main() {
final job = Job();
job.start();
try {
job.start();
} on LateInitializationError {
print('already started');
}
}The second assignment is caught only at run time. For a plain final field, the compiler can prove that the field is assigned once. For late final it cannot, so it defers the check.
A late variable that is not final can be assigned many times. With an initializer, the initializer is only the first value, used if nothing assigns to it before the first read.
The lifecycle of a late variable
Local late variables
You can also use late on local variables. A local late variable with an initializer is evaluated only if the code actually reads it.
int compute() {
print('computing');
return 42;
}
void report({required bool verbose}) {
late final int answer = compute();
print('start');
if (verbose) {
print(answer);
}
}
void main() {
report(verbose: false); // start
report(verbose: true); // start, computing, 42
}Do not add late to a local just to silence a "must be assigned" error. Dart already allows a non-late local to be declared first and assigned later, as long as every path assigns it before a read. Use late on a local only when you want laziness.
Static and top-level variables
Top-level and static variables with initializers are already lazy in Dart. They are computed on first access. late matters for them only when you want to declare one without an initializer and assign it later.
Gotchas
late with a nullable type
late and ? are independent. A late String? with no initializer is not null before assignment. It is uninitialized, and reading it throws.
class Note {
late String? text;
}
void main() {
final n = Note();
try {
print(n.text);
} on LateInitializationError {
print('uninitialized, not null');
}
n.text = null;
print(n.text); // null
}If you want "no value yet" to be a normal, readable state, use a plain nullable field instead.
You cannot ask whether it is initialized
Dart has no isInitialized check for late variables. Wrapping reads in try/catch to find out is a sign the design needs a nullable field or a different structure.
Side effects in lazy initializers
A lazy initializer runs at an unpredictable time: whenever a reader first touches it. Keep it free of side effects that depend on timing, such as reading the clock or consuming a stream. If you need the effect to happen at a known point, do it in the constructor or an explicit method.
Reading in the wrong order
The usual cause of LateInitializationError is a framework callback order you assumed. In Flutter, a State object's late field assigned in initState is safe to use in build, because the framework calls initState first. The same field read from the constructor throws.
Small run-time cost
A late field needs a way to remember whether it has been set, so reads include a check. The cost is small, but it is not zero, and a plain final field has no such check.
Choosing between late and the alternatives
| Situation | Better choice |
|---|---|
| Value can be computed from constructor arguments | Initializer list or a normal `final` field |
| Value is supplied by the caller | `required` named parameter |
| Value may legitimately be absent | Nullable field (`T?`) |
| Value is costly and may never be needed | `late final` with an initializer |
| Value depends on `this` or other fields | `late final` with an initializer, or a getter |
| Value is set by a framework callback before use | `late` or `late final` without an initializer |
Here is a case where late is unnecessary. The initializer list does the job and the compiler checks it.
class Circle {
final double radius;
final double area;
Circle(this.radius) : area = 3.14159 * radius * radius;
}
void main() {
print(Circle(2).area); // 12.56636
}Prefer this form when the value is cheap and always needed. Choose late final when it is costly, rarely used, or truly cannot be known at construction.
Summary of rules
latewithout an initializer defers assignment and checks it at run time.latewith an initializer defers computation until the first read and then caches it.late finalallows a single assignment, and with an initializer allows none.- A
lateinitializer can usethis. - Reading before initialization, or assigning twice to
late final, throwsLateInitializationError. late T?is still uninitialized until assigned. It is notnull.
Exercise
What does this program print, and in what order? Explain when _load runs.
class Cache {
late final List<int> data = load();
List<int> load() {
print('loading');
return [1, 2, 3];
}
}
void main() {
final c = Cache();
print('ready');
print(c.data.length);
print(c.data.length);
}
Show answer
It prints ready, loading, 3, 3. The late final initializer does not run when Cache() is constructed. It runs on the first read of c.data, which is inside the first print(c.data.length), so loading is printed before the first 3. The result is then cached, so the second read prints only 3 and _load is not called again.
Exercise
A teammate declares late String? nickname; in a class and checks if (nickname == null) before assigning it. What happens when this check runs on a new object, and what would you change?
Show answer
The check throws LateInitializationError, because a late field without an initializer is uninitialized until assigned, even when its type is nullable. It is not null. If "no value yet" is a normal state, declare a plain String? nickname;, which starts as null and can be checked safely. Keep late only for values that must be assigned before any read.