late
- Dart course
- Beginner
- Lesson 10/116
- 5 min
Learn deferred initialization with late.
The late keyword
late marks a variable as initialized later. You do not give a value at the declaration; you set it before first use.
Typical use: values that are expensive to compute or only known at a certain stage. For example late String description; then later description = 'Nice weather'; sets the value then.
If you use the variable before assigning, Dart throws a LateInitializationError. So late is a promise: 'I will set it, just not yet'.
Practice late variable
Declare late String description;. Then assign description = 'Nice weather'; and print it with print(description);.
Starter code
// Declare a late variableSample solution
void main() {
late String description;
description = 'Nice weather';
print(description);
}Expected output
Nice weather
When to use late?
There are two common reasons to use late: (1) The value is expensive to compute and not always needed, so late computes it on demand.
(2) The value is only known after another initialization finishes. For example a setting that becomes known only after a config file is read.
But overusing late makes code harder to follow; you must track when the value is set. Prefer var or final unless you really need late.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is late used?
- When the value is computed later Correct answer
- Only in class fields
- For every variable
- Never used
Explanation: late is for cases where you set the value later.
2 late concepts
| Term | Meaning |
|---|---|
late |
Deferred init |
final |
Immutable |
const |
Compile-time |
var |
Mutable |
3 Deferred init
____ String description;
late String description;
Explanation: With late the value is given later.