TExcelTAD
Home › Dart › Dart Null Safety

Dart Null Safety

Tony Hoare called the null reference his "billion-dollar mistake": in many languages any object variable might secretly be null, and the program crashes only when that path finally runs. Dart solves this with sound null safety — the type system tracks which values can be null, and the compiler refuses code that could dereference one.

"Sound" means the guarantee is absolute: if a variable's type is non-nullable, it is never null at runtime. The compiler can rely on that for optimisation, and you can rely on it for correctness.

Nullable vs non-nullable types

Declaration Holds Default
String name Always a String Must be assigned before use
String? name A String or null null
List<int?> A list whose elements may be null —
List<int>? A list of ints, or no list at all null

Think of T? as the union T | Null. You cannot call String methods on a String? until you prove it isn't null:

dart · try it yourself
void main() {
  String? title;
  print(title.length);
}
example.dart:3:15: Error: Property 'length' cannot be accessed on 'String?' because it is potentially null.
Try accessing using ?. instead.
  print(title.length);
              ^^^^^^
Error: AOT compilation failed
Bad state: Generating AOT kernel dill failed!

Four ways to handle a nullable value

dart · try it yourself
int lengthOf(String? text) {
  // 1. Check and promote
  if (text != null) {
    return text.length; // text is a String here
  }
  return 0;
}

void main() {
  String? maybe = DateTime(2024, 1, 1).year > 2000 ? null : 'x';

  print(lengthOf(maybe));
  print(maybe?.length);         // 2. null-aware access -> int?
  print(maybe?.length ?? 0);    // 3. default with ??
  maybe ??= 'fallback';         //    or assign a default
  print(maybe.length);          // promoted after ??=

  final colors = {'sky': 'blue'};
  print(colors['sky']!.length); // 4. assert with ! (throws if null)
}
0
null
0
8
4

Prefer them roughly in that order: promotion and ?? are safe; ! moves the check to runtime and should be rare.

Flow analysis and promotion

The compiler follows your control flow. After a null check, an early return, or a throw, the variable is promoted for the rest of the scope:

dart · try it yourself
String initials(String? first, String? last) {
  if (first == null || last == null) {
    return '??';
  }
  // both promoted to String from here on
  return '${first[0]}${last[0]}'.toUpperCase();
}

void requireName(String? name) {
  if (name == null) throw ArgumentError('name is required');
  print('Welcome, ${name.toUpperCase()}');
}

void main() {
  print(initials('ngoc', 'tran'));
  print(initials(null, 'tran'));
  requireName('Ha');
  try {
    requireName(null);
  } on ArgumentError catch (e) {
    print(e.message);
  }
}
NT
??
Welcome, HA
name is required

Why fields don't always promote

Promotion works for local variables and parameters. Public fields, getters and non-final fields don't promote, because their value could change between the check and the use (a subclass might override the getter, for example). Since Dart 3.2, private final fields do promote. For anything else, copy the field into a local:

dart · try it yourself
class Profile {
  String? bio;
  Profile(this.bio);

  int bioLength() {
    final bio = this.bio; // local copy can be promoted
    if (bio == null) return 0;
    return bio.length;
  }
}

void main() {
  print(Profile('Loves Dart').bioLength());
  print(Profile(null).bioLength());
}
10
0

Null-aware chains

?. short-circuits the rest of the chain: if the receiver is null, nothing to its right is evaluated.

dart · try it yourself
class Engine { final int hp; Engine(this.hp); }
class Car { final Engine? engine; Car([this.engine]); }

void main() {
  List<Car>? fleet = [Car(Engine(150)), Car()];

  print(fleet[0].engine?.hp.toString().padLeft(5, '.'));
  print(fleet[1].engine?.hp.toString().padLeft(5, '.'));

  List<int>? extras;
  print([1, 2, ...?extras]);
  print(extras?.first);
}
..150
null
[1, 2]
null

late and required

  • required makes a named parameter mandatory, so it can be non-nullable without a default: void send({required String to}).
  • late declares a non-nullable variable that is assigned later. Reading it too early throws LateInitializationError. See Variables.

Generics and null safety

A type parameter T can be instantiated with a nullable type, so inside generic code T is "potentially nullable". Constrain it with T extends Object if you need non-null values:

dart
T firstOr<T>(List<T> items, T fallback) => items.isEmpty ? fallback : items.first;

class Cache<K extends Object, V extends Object> { /* keys and values never null */ }

Null-safety checklist

Situation Idiom
Optional value with a sensible default value ?? defaultValue
Call a method only if present obj?.method()
Lazily fill a cache _cache ??= compute()
Several null checks Early return / throw, then use promoted values
Map lookups map[key] ?? fallback (a lookup returns V?)
You really know better than the compiler value! — and add a comment explaining why

Test yourself

What is the type of user?.name.length when name is a non-nullable String?

  1. int
  2. int?
  3. String?
  4. Never

Why might if (obj.field != null) obj.field.length fail to compile?

  1. Fields can never be null
  2. Public non-final fields are not promoted, since their value could change
  3. != doesn't work with null
  4. length doesn't exist on String

Which is the safest way to get a non-null int from int? count?

  1. count!
  2. count as int
  3. count ?? 0
  4. int(count)