Sub topic 5
Null safety: nullable lookups and nullable collections
This chapter assumes you know Dart's null safety basics: that int? allows null and int does not, and how ??, ?., and ! work on a single value. It also assumes you can read List<int>, Map<String, int>, and Set<int>. Here you will see where null shows up when you work with collections, and how to handle it without sprinkling ! everywhere.
Why collections produce nullable values
A collection's element type tells you what it holds, but some operations can fail to produce an element. The most common case is a map lookup. A map can't promise that every key you ask about exists, so operator [] returns the value type made nullable.
void main() {
final stock = <String, int>{'apple': 3, 'pear': 0};
final apples = stock['apple']; // type is int?, not int
// print(apples + 1); // compile error: 'int?' can't be used as 'int'
print(apples ?? 0); // 3
print(stock['kiwi'] ?? 0); // 0, missing key falls back to the default
if (apples != null) {
print(apples + 1); // 4, promoted to int inside the if
}
}Promotion works because apples is a local final variable. It does not work on the lookup expression itself. Writing if (stock['apple'] != null) print(stock['apple']! + 1); compiles, but it looks the key up twice and needs a !. Copy the result into a local variable first.
Four ways to handle a nullable lookup
| Technique | Example | Use when |
|---|---|---|
| Default with `??` | `stock['kiwi'] ?? 0` | A sensible default exists |
| Local variable and null check | `final n = stock[k]; if (n != null) ...` | You need to branch on presence |
| Pattern with null-check | `if (stock[k] case final n?) ...` | You want the check and the binding in one step (Dart 3) |
| Bang `!` | `stock['apple']!` | You are certain the key exists, and a crash is acceptable if not |
void main() {
final stock = <String, int>{'apple': 3};
if (stock['apple'] case final count?) {
print('have $count'); // have 3
} else {
print('out of stock');
}
final sure = stock['apple']!; // throws if the key were missing
print(sure);
}Using ! on a missing key throws a TypeError at runtime. This usually means a compile-time check was traded for a crash. Prefer ! only when the key was just inserted or checked in the same scope.
Missing key versus stored null
When the value type is itself nullable, null becomes ambiguous. A lookup returns null both for an absent key and for a key whose stored value is null.
void main() {
final scores = <String, int?>{'ana': 90, 'bo': null};
print(scores['bo']); // null, key exists, value is null
print(scores['cy']); // null, key does not exist
print(scores.containsKey('bo')); // true
print(scores.containsKey('cy')); // false
}If the difference matters, test with containsKey. Often a better fix is to avoid nullable values in the map altogether. Store a non-null sentinel such as -1, or leave the entry out of the map, so that null means only "absent".
Other operations that return nullable values
Map lookups are not the only source. These return a nullable type because the answer might not exist:
map.remove(key)returnsV?, the removed value ornull.set.lookup(element)returnsE?, the stored equal element ornull.iterable.firstOrNull,lastOrNull, andsingleOrNullreturnE?instead of throwing on an empty collection. They are indart:corefrom Dart 3.0.
Other operations do not use null to signal failure. They throw, or return a sentinel number:
void main() {
final names = ['ada', 'bob', 'cy'];
print(names.indexOf('zed')); // -1, a sentinel, not null
print(names.indexWhere((n) => n.startsWith('z'))); // -1
print(names.firstWhere((n) => n.startsWith('z'), orElse: () => 'none')); // none
print(names.where((n) => n.startsWith('z')).firstOrNull); // null
try {
names.firstWhere((n) => n.startsWith('z')); // no orElse
} on StateError {
print('no element');
}
try {
print(names[10]);
} on RangeError {
print('index out of range'); // indexing never returns null
}
}Indexing a list with a bad position throws a RangeError. It never returns null. If you need "element or nothing" for an index, check index < list.length first, or use firstOrNull for the first element.
Nullable elements versus nullable collections
The ? can sit in two places, and they mean different things.
| Type | The collection | The elements |
|---|---|---|
| `List<int>` | Never null | Never null |
| `List<int?>` | Never null | May be null |
| `List<int>?` | May be null | Never null |
| `List<int?>?` | May be null | May be null |
Read the type from the outside in. The ? after > belongs to the whole list. The ? inside the angle brackets belongs to each element.
Nullable collections
Use ?., ?[], and ...? to work through a collection that might be null. Each stops and yields null (or contributes nothing, for the spread) when the collection is null.
int countItems(List<String>? items) => items?.length ?? 0;
String? secondItem(List<String>? items) {
if (items == null || items.length < 2) return null;
return items[1];
}
void main() {
List<String>? none;
final some = <String>['a', 'b', 'c'];
print(countItems(none)); // 0
print(countItems(some)); // 3
print(none?.firstOrNull); // null
print(some.firstOrNull); // a
print(secondItem(none)); // null
print(secondItem(some)); // b
Map<String, int>? config;
print(config?['retries']); // null, the whole expression short-circuits
final merged = [...?none, ...some];
print(merged); // [a, b, c]
}Note that none?[1] would give null for a null list but still throw a RangeError on a short, non-null list. The ? guards against a null collection only. It does not guard against a bad index.
A frequently useful pattern is to replace a nullable collection with an empty one at the boundary, so the rest of the code never checks again:
void printAll(List<String>? maybeNames) {
final names = maybeNames ?? const <String>[];
for (final n in names) {
print(n);
}
}Better still, make the parameter non-nullable with a default of const [] when callers can reasonably omit it. An empty list says "nothing here" just as well as null does, and it needs no check.
Nullable elements
A List<int?> is useful when positions matter and some are unfilled. List<int>.filled(3, null) does not compile, but this does:
void main() {
final slots = List<int?>.filled(3, null);
slots[1] = 42;
print(slots); // [null, 42, null]
final raw = <int?>[1, null, 3, null, 5];
final clean = raw.whereType<int>().toList();
print(clean); // [1, 3, 5], type is List<int>
final alsoClean = raw.nonNulls.toList(); // Dart 3.0 and later
print(alsoClean); // [1, 3, 5]
final total = raw.fold<int>(0, (sum, n) => sum + (n ?? 0));
print(total); // 9
}Both whereType<int>() and nonNulls change the static type to Iterable<int>. A plain raw.where((n) => n != null) filters correctly at runtime, but the result is still Iterable<int?>, so the compiler keeps complaining. Use whereType or nonNulls when you need the type to change as well.
Updating maps without nullable results
Several map methods are designed so you rarely have to touch a nullable value:
void main() {
final counts = <String, int>{};
for (final word in ['a', 'b', 'a']) {
counts.update(word, (n) => n + 1, ifAbsent: () => 1);
}
print(counts); // {a: 2, b: 1}
final list = counts.putIfAbsent('c', () => 0); // returns int, not int?
print(list); // 0
counts['d'] ??= 10; // assigns only if the lookup is null
print(counts['d']); // 10
}putIfAbsent returns the non-null value type V, because it always leaves a value in the map. update throws if the key is absent and you gave no ifAbsent. This is the counting idiom you will use most often.
Common errors
- Writing
map[key]!in code that handles user input or file data. The key can be missing, and you get aTypeError. - Expecting
list[i]to returnnullfor a bad index. It throws aRangeError. - Using
where((x) => x != null)and then passing the result to something that needsIterable<int>. - Confusing
List<int?>withList<int>?. The first has a list that is always there, the second may have no list at all. - Treating
nullfrom aMap<K, V?>as "missing". UsecontainsKeywhen the difference matters.
Exercise
Given final data = <String, int?>{'a': 1, 'b': null};, what do data['b'], data['z'], and data.containsKey('z') return, and how would you tell a stored null from a missing key?
Show answer
data['b'] returns null and data['z'] returns null, because both a stored null and a missing key give null. data.containsKey('z') returns false. To tell them apart, call containsKey: data.containsKey('b') is true (stored null), while data.containsKey('z') is false (missing).
Exercise
What is the type of raw.where((n) => n != null) when raw is List<int?>, and what should you use to get an Iterable<int>?
Show answer
It is Iterable<int?>, since where filters values but does not change the element type. Use raw.whereType<int>() or raw.nonNulls (Dart 3.0 and later) to get an Iterable<int>.