late
- Dart course
- Intermediate
- Lesson 21/116
- 5 min
Learn deferred initialization with late.
late
Sometimes you want to give a field its initial value later, not in the constructor. The late keyword declares that a field will be initialized later; by the first read, its value must be set.
Example: class Config { late String apiKey; void load(String key) { apiKey = key; } }. Here apiKey is declared late; the load method assigns its value when called. If apiKey is read before load runs, a LateInitializationError is thrown. This shape fits heavy resources that should be prepared only when needed and helps resolve circular dependencies.
late and lazy initialization
The late keyword can also take a body; then the field is initialized lazily: on first read the body runs and the result is cached.
Example: late final heavy = _compute();. Here heavy runs _compute() on first read and caches the result; later reads return the same value. If heavy is never read, _compute never runs. This shape is a clean way to do expensive calculations only when needed. The late final combo guarantees that the value is computed once and cached.
Practice Add a late field to Config
Define a class named Config. Add a late String apiKey field. Write a void load(String key) { apiKey = key; } method. In main, create an instance with var c = Config();, call c.load('abc123') and print with print(c.apiKey).
Starter code
// Define the Config class
// Add a late apiKey field and a load method
void main() {
// Create a Config instance, call load('abc123') and print c.apiKey
}Sample solution
// Define the Config class
class Config {
late String apiKey;
void load(String key) {
apiKey = key;
}
}
void main() {
var c = Config();
c.load('abc123');
print(c.apiKey);
}Expected output
abc123
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does a late field throw an error?
- When the constructor is called
- When declared as static
- When used with final
- When read before being set Correct answer
Explanation: A late field throws LateInitializationError if read before being set.
2 Match the late parts
| Term | Meaning |
|---|---|
late |
Keyword |
apiKey |
Field assigned later |
load |
Method that assigns |
3 Add the late keyword
class Config {
____ String apiKey;
void load(String key) {
apiKey = key;
}
}
class Config {
late String apiKey;
void load(String key) {
apiKey = key;
}
}
Explanation: late declares a field that will be initialized later.