typestar

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

  1. late String leader promises assignment before first read.
  2. late final with an initializer runs lazily, on first touch.
  3. The print shows the fetch happens exactly once.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Null safety, step 18 of 27 in Language basics.

← Previous Next →