Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 61 ยท Types and Operators

late Variables and Lazy Initialization

Learn the Dart late keyword: declare non-nullable variables that are assigned later, use late final and lazy initializers, and avoid LateInitializationError.

Null safety says a non-nullable variable must have a value before you read it. Usually that is easy: you give it a value on the same line. But sometimes the value cannot be computed at the declaration, because it depends on something that happens later, or because computing it is expensive and you may never need it. The late modifier is Dart's tool for those cases.

late is a promise to the compiler: "I will assign this variable before anyone reads it." The compiler trusts you, and checks the promise at runtime. This lesson shows the three uses of late, how to avoid its main failure, and how to decide when a better design avoids it altogether. Dart code is read-only; TypeScript stand-ins let you try the same behavior.

late without an initializer

Normally the compiler insists that a non-nullable variable be set at once. With late, you can postpone the assignment:

DART
late String description;

void main() {
  description = 'Set after the program started';
  print(description);
}
TEXT
Set after the program started

Without late, the declaration String description; would be an error, because a String cannot start out as null. With late, the variable is allowed to exist unassigned. The variable is checked every time it is read. If you read it too early, you get a LateInitializationError:

DART
late String description;

void main() {
  print(description);   // throws before anything is printed
}
TEXT
Unhandled exception:
LateInitializationError: Field 'description' has not been initialized.

(For a local variable the message says "Local 'description' ..." instead.) This is a runtime error, not a compile-time error. That is the price of late: you trade a compiler guarantee for your own promise.

stateDiagram-v2
    [*] --> Unassigned: declared with late
    Unassigned --> Assigned: first assignment
    Unassigned --> Error: read before assignment
    Assigned --> Assigned: later reads are fine
    Error --> [*]: LateInitializationError

A late variable is unassigned until its first assignment; reading it earlier throws.

Typical use: setup that happens later

A common case is a class whose field can only be filled in after construction, for example in a framework's startup method:

DART
class Greeter {
  late String name;      // assigned in setUp(), never null afterwards

  void setUp(String value) {
    name = value;
  }

  String greet() => 'Hello, $name!';
}

void main() {
  var g = Greeter();
  g.setUp('Dart');
  print(g.greet());      // Hello, Dart!
}

Compare this with the alternative, String? name;. Every use of a nullable name would need a check or a !. With late String name, the rest of the class can treat it as a plain String. That convenience is the reason late exists. It is also the reason to be careful: the compiler no longer protects you from reading too early.

TypeScript A late field and its guard (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

late final: assign exactly once

You can combine late with final. A late final variable may be assigned one time, at any point, and then never changes. This is perfect for values known only after some work is done:

DART
late final int port;

void main() {
  port = 8080;          // first assignment: fine
  print(port);
  port = 9090;          // second assignment: LateInitializationError
}
TEXT
8080
Unhandled exception:
LateInitializationError: Field 'port' has already been initialized.

A plain final field must be set by the time the constructor finishes. A late final field can be set later, but only once, so it keeps immutability while giving you freedom about when.

Lazy initialization with an initializer

The third use is the most elegant. If you put an initializer on a late variable, it does not run when the object is created or the program starts. It runs the first time the variable is read, and the result is remembered.

DART
int expensiveSum() {
  print('computing...');
  var total = 0;
  for (var i = 1; i <= 1000; i++) {
    total += i;
  }
  return total;
}

late final int cached = expensiveSum();

void main() {
  print('start');
  print(cached);     // computing... then 500500
  print(cached);     // 500500, no recomputation
}
TEXT
start
computing...
500500
500500

Because the work waits until the first read, a program that never touches cached never pays for it. Another benefit: a late initializer is allowed to use this, which ordinary field initializers cannot do.

DART
class Report {
  final List<int> numbers;
  Report(this.numbers);

  late final int total = numbers.fold(0, (a, b) => a + b);   // uses this.numbers
}
TypeScript Lazy initialization and caching (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Pitfalls and alternatives

late is useful, but it has sharp edges worth knowing.

  • Reading too early. The error appears at runtime, perhaps only on one code path. If the variable is assigned in a method, make sure that method always runs first.
  • Hidden cost on every read. A late variable carries an "initialized?" flag that is checked on each access. The cost is tiny, but it is real, and it is why late is not a default choice.
  • Initializer order. Lazy initializers run when first read, which may be later than you expect. If the initializer has side effects (printing, opening a file), the timing can surprise you.
  • Not a replacement for constructors. If the value is known when the object is created, pass it to the constructor. A final field set by a constructor is checked by the compiler, a late one is not.

Before writing late, ask three questions. Can I give the variable a value right now? Can I pass it through the constructor? Would a nullable type with a proper check be clearer? Only if the answers are no, late is the right tool. Top-level and local variables can be late too, but the field case is by far the most common.

You can also write late on a local variable to declare it before the branch that assigns it, as long as every path assigns it before it is read. Often a plain final with an if expression or a conditional is cleaner.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does late String name; promise the compiler?

    late lets a non-nullable variable start unassigned. You promise to assign it before any read; Dart checks the promise at runtime.
  2. 2. What happens if you read a late variable before assigning it?

    The error is thrown when the read executes, not when the program is compiled.
  3. 3. How many times can a late final variable be assigned?

    late final allows a single assignment at any time after declaration. A second assignment throws a LateInitializationError.
  4. 4. When does the initializer of late final int cached = expensiveSum(); run?

    A late variable with an initializer is lazy, so the expression runs on first access and the result is stored for later reads.
  5. 5. Which is usually the best choice when a value is known at construction time?

    A final field assigned by the constructor is verified by the compiler, so it is safer than late.

Summary

  • late lets a non-nullable variable be assigned after its declaration; reading it first throws a LateInitializationError.
  • late final can be assigned exactly once, at a time you choose.
  • A late variable with an initializer is lazy: it computes on first read and caches the result, and the initializer may use this.
  • The checks happen at runtime, so prefer constructors, plain final or nullable types when they fit.

Next, step back and look at how all of Dart's types fit together in The Type System: dynamic, Object and Type Inference.