What is late?
The late keyword declares a non-nullable variable that will be initialized later (before it is first used). It tells Dart: "I promise this will be initialized before anyone reads it — skip the compile-time check."
late String name; // not initialized yet — no compile error
void setup() {
name = 'Alice'; // initialized before use
}
void main() {
setup();
print(name); // Alice — safe
}
When to Use late
- Class fields that are initialized in a method (not the constructor)
- Variables initialized after an async operation completes
- Expensive computations you want to delay (lazy initialization)
- Flutter: accessing controllers or services set up in
initState()
Lazy Initialization
When a late variable has an initializer, the initializer runs only the first time the variable is accessed:
late String expensiveResult = computeExpensiveValue();
String computeExpensiveValue() {
print('Computing...');
return 'result';
}
void main() {
print('Before access');
print(expensiveResult); // Computing... then result
print(expensiveResult); // result (not computed again)
}
Output:Before access
Computing...
result
result
Example
class DatabaseService {
late String connectionString; // set during init, not constructor
void initialize(String host, String db) {
connectionString = 'host=$host;db=$db';
}
void query(String sql) {
print('Running on $connectionString: $sql');
}
}
void main() {
var db = DatabaseService();
db.initialize('localhost', 'myapp');
db.query('SELECT * FROM users');
}
Output:Running on host=localhost;db=myapp: SELECT * FROM users
⚠️ Common Mistakes
- Reading a
late variable before it is initialized throws a LateInitializationError at runtime.
- Using
late to avoid initializing a variable — use nullable T? instead if the variable may genuinely never be set.
🧠 Quiz
1. What error occurs if you read a late variable before initializing it?
- A) NullPointerException
- B) LateInitializationError ✅
- C) TypeError
- D) Compile error
2. When does the initializer of a lazy late variable run?
- A) At program start
- B) When the variable is declared
- C) On first access ✅
- D) Every time it is accessed
Summary
The late keyword defers initialization of non-nullable variables. It supports lazy initialization (only computed on first access). Use it for fields initialized in lifecycle methods or for expensive computations. Reading before initialization throws LateInitializationError.