DartAdvanced 2 min read

Dart type promotion, Never and late: make invariants visible

Use guard clauses and precise return contracts instead of unnecessary casts or unchecked late initialization.

On this page

A guard can establish an invariant for the rest of a function. Let flow analysis carry that information rather than repeatedly casting. Use late only when a value genuinely has a deferred initialization lifecycle you can explain.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
Never invalidIdentifier() => throw const FormatException('Expected a non-empty ID.');

String readIdentifier(Object? value) {
  if (value is! String || value.trim().isEmpty) invalidIdentifier();
  return value.trim();
}

void main() {
  print(readIdentifier(' INV-7 '));
  late final String reportTitle;
  reportTitle = 'Weekly invoices';
  print(reportTitle);
}

Follow the data and control flow

Never communicates that the failure helper does not return normally. After the guard, the value is a usable String. The late final local demonstrates deferred assignment followed by one valid read, but a normal initialized final variable would be simpler when the value is already available.

Object? represents an unknown possibly-null value. dynamic suppresses many static checks, and void describes an ignored result contract. These types solve different problems; choosing dynamic is not a general solution to an analyzer complaint.

A mistake to avoid

Reading an uninitialized late variable fails at runtime, so replacing every nullable field with late can hide lifecycle defects. Promotions can also be limited by mutation and member access; capture a stable local or redesign the boundary rather than applying a blind non-null assertion.

Practice and verification

Pass null, an integer and a blank string. Verify each fails at the intended boundary. Remove late by reorganizing initialization and compare clarity. Explain why a function that sometimes returns an error string cannot honestly declare Never.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.