late and lazy in Dart
Defer initialization without going nullable.
// late defers initialization past the constructor without going
// nullable; a late final with an initializer runs lazily, on first use.
class SurveyDay {
late final String weatherNote = _fetchWeather();
late String leader;
String _fetchWeather() {
print('(fetching the forecast now)');
return 'light rain, SW 12';
}
}
void main() {
final day = SurveyDay();
day.leader = 'Rae';
print('Leader: ${day.leader}');
// First touch triggers the lazy initializer, exactly once.
print('Weather: ${day.weatherNote}');
print('Again: ${day.weatherNote}');
}
How it works
late String leaderpromises assignment before first read.late finalwith an initializer runs lazily, on first touch.- The print shows the fetch happens exactly once.
Keywords and builtins used here
StringSurveyDayclassfinallatereturnvoid
The run, in numbers
- Lines
- 20
- Characters to type
- 548
- Tokens
- 95
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 88 seconds.
Step 3 of 3 in Null safety, step 18 of 27 in Language basics.