Skip to content
AgileLogics
6 min read

Null Safety

Prerequisites: Data types and type inference

null means "no value". In many languages any variable can unexpectedly be null, and using it crashes the program. Dart's sound null safety prevents this: the compiler guarantees that a non-nullable variable never holds null.

Real-world analogy: a nullable value is a parcel that might be an empty box. Dart makes you check before you unpack it.

Nullable and non-nullable types

By default, a type can't hold null. Add ? to allow it:

void main() {
  String name = 'Ada';
  String? nickname;

  print(name.length);
  print(nickname);
}
3
null

A nullable variable with no initial value starts as null. A non-nullable variable must be given a value before it's used.

You can't use a nullable value directly

void main() {
  String? nickname = 'Addy';
  nickname = null;
  print(nickname.length);
}
hello.dart:4:18: Error: Property 'length' cannot be accessed on 'String?' because it is potentially null.

That error is Dart protecting you: nickname might be null, so you must handle that case first. The next lesson shows the tools for it.

Where nulls come from

Many operations return a nullable value when something might not exist:

void main() {
  print(int.tryParse('42'));
  print(int.tryParse('forty'));
  print({'a': 1}['b']);
  print(<int>[].firstOrNull);
}
42
null
null
null

int.tryParse returns null instead of throwing, and looking up a missing map key gives null.

Common mistakes

  • Making everything nullable "just in case". Only add ? when a value can genuinely be missing.