Sub topic 10
Nullable Elements, Nullable Collections, and Map Lookups
This chapter assumes you know Dart variables, generic types, collections, and null-aware operators. The key skill is separating two different questions:
- Can the collection reference itself be
null? - Can an item inside the collection be
null?
These questions produce different types and require different checks.
Two kinds of nullability
List<int?> means the list must exist, but its elements may be null. List<int>? means the list itself may be null, but every element in an existing list must be an int.
| Type | Can the list be null? | Can an element be null? |
|---|---|---|
| `List<int>` | No | No |
| `List<int?>` | No | Yes |
| `List<int>?` | Yes | No |
| `List<int?>?` | Yes | Yes |
void main() {
List<int> scores = [10, 20];
List<int?> scoresWithGaps = [10, null, 20];
print(scoresWithGaps[1]); // null
List<int>? optionalScores;
print(optionalScores?.length); // null
List<int?>? optionalScoresWithGaps;
print(optionalScoresWithGaps?.length); // null
}The expression scoresWithGaps[1] has type int?, so code that uses it as an int must first handle the null case.
flowchart TD
A["List<int?>"] --> B["List exists"]
A --> C["Each element may be null"]
D["List<int>?"] --> E["List may be null"]
D --> F["Elements are non-null int"]caption: How nullability applies to a list alt: A diagram contrasting nullable list elements with a nullable list reference
Map lookups are nullable
A map lookup returns a nullable value even when the map's value type is non-nullable:
void main() {
final ages = <String, int>{
'ann': 30,
'ben': 25,
};
final age = ages['sam']; // int?
print(age ?? -1); // -1
}The key might not exist, so ages['sam'] cannot have type int. It has type int?. The ?? operator supplies a fallback when the lookup returns null.
You can also check the result with flow analysis:
int ageOrDefault(Map<String, int> ages, String name) {
final age = ages[name];
if (age == null) {
return 0;
}
return age; // age is promoted to int
}
void main() {
print(ageOrDefault({'ann': 30}, 'sam')); // 0
}A map can also intentionally store nullable values. In that case, both a missing key and a present key with a null value produce null from []. Use containsKey when those cases must be distinguished.
void main() {
final notes = <String, String?>{
'ann': null,
};
print(notes['ann']); // null
print(notes.containsKey('ann')); // true
print(notes.containsKey('sam')); // false
}Spreading a nullable collection
The null-aware spread operator, ...?, adds the elements of a collection only when that collection is not null.
void main() {
final requiredTags = <String>['dart', 'null-safety'];
List<String>? optionalTags;
final tags = [
...requiredTags,
...?optionalTags,
];
print(tags); // [dart, null-safety]
}Without ...?, the regular spread operator would try to spread a null value and fail. You can also use ?? to choose an empty collection:
void main() {
List<int>? extra = [3, 4];
final numbers = [
1,
2,
...(extra ?? <int>[]),
];
print(numbers); // [1, 2, 3, 4]
}Both forms are useful. ...? is shorter when you only need to skip a null collection. The ?? form is useful when you need to pass the resulting collection to another expression or function.
Common mistakes
List<int?>is not the same asList<int>?.- Checking
list != nullonly proves that the list exists. It says nothing about nullable elements. - Checking
list[index] != nulllets you use that particular value after promotion, but repeated indexing may not be promoted reliably. Copy it to a local variable. - A missing map key is not an error by itself. Decide whether a fallback, an early return, or an exception is appropriate.
Exercise
What are the types of items, items[0], and lookup in this code? List<int?>? items; final first = items?.first; final lookup = <String, int>{}['x'];
Show answer
items has type List<int?>?. items?.first has type int?, because the list may be null and its first element may be null. lookup has type int?, because the key may be absent.