late
- Dart course
- Beginner
- Lesson 74/116
- 5 min
Learn deferred initialization with late.
The late keyword
The late keyword lets you declare a variable without an initial value, as long as you assign one before first use. Example: late String description;.
This provides deferred initialization without going nullable. The variable stays non-nullable; no null check is needed. But if you read it before assigning, it throws at runtime.
late is especially handy for running an expensive computation only when needed — for example, loading a config file on first access. This pattern is called lazy initialization.
late vs nullable
late and ? serve different purposes. late String name; says name will be assigned later but stays non-nullable. String? name; says name may be null.
With late, no null check is needed; you treat the value as assigned. With nullable, every access must consider the null risk.
Pick based on the data: use late when a value will definitely exist but is not available yet; use nullable when the value may genuinely be absent.
Practice Use late
Declare a late String description. Then assign description = 'Merhaba Dart' and print it with print(description).
Starter code
void main() {
// declare a late variable
// assign and print
}Sample solution
void main() {
late String description;
description = 'Merhaba Dart';
print(description);
}Expected output
Merhaba Dart
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the late concepts
| Term | Meaning |
|---|---|
late |
Deferred init |
first use |
When to assign |
non-nullable |
Type trait |
lazy |
Lazy init |
2 When does a late variable throw?
- At declaration
- Always
- Never
- If read before assigned Correct answer
Explanation: a late variable must be assigned before first read, else it throws.
3 late declaration
void main() {
____ String description;
description = 'Merhaba';
print(description);
}
void main() {
late String description;
description = 'Merhaba';
print(description);
}
Explanation: late marks deferred initialization.