Sub topic 10
Nullable Elements, Nullable Collections and Map Lookups
This chapter assumes you know the T versus T? distinction, the null-aware operators ?., ?? and ??=, and how a null check promotes a local variable. Here you apply them to collections. You will see where ? can sit in a collection type, why Map lookups return a nullable value, and how to turn nullable data into non-nullable data safely.
Three places a question mark can go
A collection type has two spots where ? can appear: on the element type and on the collection itself. They answer different questions.
| Type | The list can be null | Elements can be null |
|---|---|---|
| `List<int>` | No | No |
| `List<int?>` | No | Yes |
| `List<int>?` | Yes | No |
| `List<int?>?` | Yes | Yes |
The first question is "is there a list at all?" The second is "does every slot hold a value?" Read the type from the outside in: List<int>? is "maybe a list of ints", and List<int?> is "a list of maybe-ints".
int countGaps(List<int?> items) {
var gaps = 0;
for (final item in items) {
if (item == null) gaps++;
}
return gaps;
}
int? firstOrNullLength(List<int>? items) => items?.length;
void main() {
List<int?> withGaps = [1, null, 3];
print(withGaps.length); // 3, the list exists and has three slots
print(countGaps(withGaps)); // 1
print(firstOrNullLength(null)); // null, there is no list
print(firstOrNullLength([])); // 0, an empty list is not null
}The last two lines show a common design mistake. An empty list and a missing list are different states. In most APIs, prefer a non-nullable List<int> and return an empty list for "nothing". Use List<int>? only when "absent" carries a meaning that "empty" does not, such as "the user never answered" versus "the user chose nothing".
Each layer needs its own handling
When both layers are nullable, you must deal with each one. The compiler enforces this.
int? firstElement(List<int?>? items) {
return items?.first; // null if items is null OR if the first element is null
}
void main() {
print(firstElement(null)); // null
print(firstElement([null, 2])); // null
print(firstElement([5, 2])); // 5
}The result type is int?, and the caller cannot tell from the value alone which layer was null. If that distinction matters, check the layers separately and return something richer than a bare int?.
Safe indexing with `?[]`
The ?[] operator indexes a collection only if it is not null. Like ?., it short-circuits: if the receiver is null, the rest of the chain is skipped.
bool? firstIsEven(List<int>? items) {
return items?[0].isEven; // if items is null, .isEven is never evaluated
}
void main() {
print(firstIsEven(null)); // null
print(firstIsEven([4])); // true
}?[] protects against a null collection only. It does not protect against a bad index. items?[0] on an empty, non-null list still throws a RangeError. It also works with Map, which leads to the next topic.
Map lookups always return a nullable value
The [] operator on a Map<K, V> has the return type V?. The key might not be in the map, and Dart reports that absence as null. This is true even when V is non-nullable.
void main() {
final stock = <String, int>{'apple': 3};
final pears = stock['pear']; // type is int?
print(pears); // null
print(stock['pear'] ?? 0); // 0
// print(stock['apple'] + 1); // Error: 'int?' has no operator '+'
final apples = stock['apple'];
if (apples != null) {
print(apples + 1); // 4, apples is promoted to int
}
}The commented-out line is the error you will meet most often. Dart cannot know that 'apple' is present, so the compiler requires you to handle the missing case. Pick the approach that fits the situation:
- Use
??when a default value is reasonable:stock['pear'] ?? 0. - Copy the lookup into a local variable and test it, as
applesdoes above. - Use a pattern when you want a value or a branch:
if (stock['apple'] case final n?) { ... }. - Use
!only when your code has already guaranteed the key exists, for example right aftercontainsKey. Even then, a local variable or a pattern is usually clearer.
Promotion does not work on stock['apple'] directly. Each [] call is a fresh method call that the compiler cannot assume returns the same thing twice. This is the same reason mutable fields do not promote. Store the result in a local variable first.
Maps whose values are nullable
Now the lookup result is ambiguous. With Map<String, bool?>, a lookup returns bool?, and null can mean either "key missing" or "key present with a null value".
void main() {
final prefs = <String, bool?>{'dark': null, 'sound': true};
print(prefs['dark']); // null, key present, value null
print(prefs['missing']); // null, key absent
print(prefs.containsKey('dark')); // true
print(prefs.containsKey('missing')); // false
}When the difference matters, call containsKey. Better still, avoid storing null as a value and model the third state explicitly with an enum such as unset, on and off. Doing so removes the ambiguity from the type itself.
The diagram summarizes how to choose a lookup strategy.
Building collections that may contain nulls
The spread `...?`
A plain spread ...x requires a non-null collection. The null-aware spread ...?x treats a null collection as empty. It works for lists, sets and maps.
void main() {
final base = <int>[1, 2];
List<int>? extra;
print([...base, ...?extra]); // [1, 2]
final defaults = <String, int>{'a': 1};
Map<String, int>? overrides;
print({...defaults, ...?overrides}); // {a: 1}
}Notice that ...? guards the collection, not its elements. Spreading a List<int?> into a List<int> is still a type error, because the elements might be null.
Null-aware elements
From Dart 3.8, a ? before an element inserts it only when it is not null. Earlier SDKs reject this syntax, so check your environment: sdk: constraint first.
void main() {
String? middle;
final names = ['Ada', ?middle, 'Lovelace']; // type is List<String>
print(names); // [Ada, Lovelace]
}On older SDKs, write if (middle != null) middle inside the literal. It does the same job, and the element is promoted to String inside the if.
Removing nulls from a `List<int?>`
You cannot assign a List<int?> to a List<int>, because the compiler cannot prove that no element is null. You must filter, and the filter has to change the type, not only the contents.
void main() {
final raw = <int?>[1, null, 3, null];
final viaWhereType = raw.whereType<int>().toList(); // List<int>
final viaNonNulls = raw.nonNulls.toList(); // List<int>
final viaLiteral = <int>[
for (final x in raw)
if (x != null) x,
];
print(viaWhereType); // [1, 3]
print(viaNonNulls); // [1, 3]
print(viaLiteral); // [1, 3]
final stillNullable = raw.where((x) => x != null).toList();
print(stillNullable.runtimeType); // List<int?>
}The last lines are a classic trap. where((x) => x != null) removes the nulls at runtime, but its result type is still Iterable<int?>, because the compiler does not infer types from a closure's logic. Use whereType<int>() or nonNulls (Dart 3.0 and later) when you need the type to change.
A cast such as raw as List<int> is not a filter. It compiles but throws a TypeError at runtime if the list's actual type argument is int?. The same holds for .cast<int>(), which fails later, when the first null element is read.
Nullable results from collection methods
Many collection methods return a nullable value instead of throwing, and the type tells you so. The firstOrNull, lastOrNull, singleOrNull and elementAtOrNull getters (in dart:core since Dart 3.0) all return T?.
void main() {
final scores = <int>[];
// print(scores.first); // Throws StateError at runtime
print(scores.firstOrNull); // null
print(scores.firstOrNull ?? 0); // 0
print(scores.elementAtOrNull(5)); // null
}Prefer these over catching exceptions when "no element" is an expected case. Prefer plain first when an empty collection would be a bug, so the failure is loud.
Generics and nullability
A type parameter can be instantiated with a nullable type. Inside a generic function, T may therefore be int or int?, and you cannot assume either.
T? findFirst<T>(Iterable<T> items, bool Function(T) test) {
for (final item in items) {
if (test(item)) return item;
}
return null;
}
void main() {
print(findFirst<int>([1, 2, 3], (n) => n > 1)); // 2
print(findFirst<int?>([null, 5], (n) => n == null)); // null
}The second call shows the ambiguity again. The result is null because the match was a null element, not because nothing matched. If you want callers to pass only non-nullable types, bound the parameter: T extends Object. Then findFirst<int?> becomes a compile-time error, and a null result always means "not found".
Common mistakes
- Writing
map[key]!everywhere. A missing key then crashes with a null check error that says nothing about which key was absent. Use??, a pattern, or an explicit error message. - Reading
nullfrom aMap<K, V?>as "missing". UsecontainsKeyor remove the nullable value type. - Using
where((x) => x != null)and expecting a non-nullable result. UsewhereTypeornonNulls. - Choosing
List<T>?where an empty list would do. Every caller must then handle two "empty" states. - Expecting
list?[i]to prevent index errors. It guards only against a null list.
Exercise
Given final inventory = <String, int?>{'bolt': null, 'nut': 4};, what are the types and values of inventory['bolt'], inventory['screw'] and inventory['nut']? How can you tell the first two apart?
Show answer
All three expressions have type int?. The values are null, null and 4. inventory['bolt'] is null because the key is present with a null value, and inventory['screw'] is null because the key is absent. Tell them apart with inventory.containsKey('bolt') (true) and inventory.containsKey('screw') (false).
Exercise
Write a function List<int> cleaned(List<int?>? input) that returns the non-null elements of input, or an empty list when input is null. Use at least one operator or method from this chapter, and explain why input?.where((x) => x != null).toList() would not compile as the return value.
Show answer
One solution is List<int> cleaned(List<int?>? input) => input?.nonNulls.toList() ?? [];. Another is [...?input?.whereType<int>()]. The where version fails for two reasons. Its result is List<int?>?, which is assignable to neither List<int> nor a non-nullable return type, because where does not change the element type and ?. makes the whole result nullable. Without ?? [] the null case is also unhandled.