๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Dart Late Variables

A late variable is a non-nullable variable that gets its value after its declaration. The value must be in place before the variable is read.

Declared now, filled later

title is declared with late and no value. The next line assigns a value, and the print then reads it safely.

void main() {
  late String title;
  title = 'Reports';
  print(title);
}

Computed on first read

The initializer calls buildLabel, but nothing runs at the declaration. The made line prints first, and the computed line appears only when label is read.

String buildLabel() {
  print('computed');
  return 'data';
}

void main() {
  late final String label = buildLabel();
  print('made');
  print(label);
  print(label);
}

A late final filled once

limit is a late final variable filled by a plain assignment. The print reads the stored value and doubles it.

void main() {
  late final int limit;
  limit = 10;
  print(limit * 2);
}

Two late variables in order

Both variables are declared before either one is filled. Each assignment lands before the print reads the pair.

void main() {
  late String first;
  late String second;
  first = 'one';
  second = 'two';
  print('$first $second');
}

Example

String loadName() {
  print('loading');
  return 'Ana';
}

void main() {
  late final String name = loadName();
  print('start');
  print(name);
  print(name.length);
}

Key points

  • The late keyword declares a non-nullable variable without giving it a value yet.
  • A late variable must be assigned before it is read.
  • A late final variable with an initializer computes its value on the first read, not at the declaration.
  • That lazy computation runs only once, and later reads reuse the stored value.
  • Reading a late variable before its assignment fails at run time, so code assigns first and reads after.

In this example, the late final variable name waits for its first read. The first print shows start before any loading line appears. Reading name runs loadName once and shows Ana, and the length read reuses the stored value and shows 3.

Note

late suits values that are set up once, shortly after the program starts.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

When does a late final variable with an initializer compute its value?