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:
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
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:
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:
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.
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
requiredmakes a named parameter mandatory, so it can be non-nullable without a default:void send({required String to}).latedeclares a non-nullable variable that is assigned later. Reading it too early throwsLateInitializationError. 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:
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?
- int
- int?
- String?
- Never
Why might if (obj.field != null) obj.field.length fail to compile?
- Fields can never be null
- Public non-final fields are not promoted, since their value could change
!=doesn't work with nulllengthdoesn't exist on String
Which is the safest way to get a non-null int from int? count?
- count!
- count as int
- count ?? 0
- int(count)