Sub topic 5
Null safety: nullable lookups and nullable collections
This chapter assumes that you know Dart variables, generics such as List<int>, and basic null safety. In Dart, null means that a value is absent. A nullable type is marked with ?, such as int? or List<String>?.
Map lookups are nullable
A map lookup can fail because the key might not exist. Therefore, the result of map[key] is nullable, even when the map's values are not nullable.
void main() {
final stock = <String, int>{
'apple': 3,
'pear': 0,
};
final appleCount = stock['apple']; // int?
final kiwiCount = stock['kiwi']; // int?, because the key is absent
print(appleCount); // 3
print(kiwiCount); // null
}The expression stock['kiwi'] has type int?, not int. You must handle the possible null before using the value as a non-null integer.
The null-coalescing operator, ??, supplies a fallback:
void main() {
final stock = <String, int>{'apple': 3};
final requested = stock['kiwi'] ?? 0;
print('Kiwi stock: $requested'); // Kiwi stock: 0
}Use containsKey when you need to distinguish an absent key from a key whose value is null.
void main() {
final values = <String, int?>{
'missing': null,
};
print(values['missing']); // null
print(values['unknown']); // null
print(values.containsKey('missing')); // true
print(values.containsKey('unknown')); // false
}The ! operator tells Dart that a nullable value is definitely non-null. It should be used only when your program has already established that fact. Otherwise, it can throw an exception at runtime.
Nullable collections and nullable elements
These two declarations mean different things:
List<String>?is a nullable list. The list itself may benull, but every element must be a non-nullString.List<String?>is a non-null list whose elements may individually benull.List<String?>?allows both the list and its elements to benull.
void printNames(List<String>? names) {
if (names == null) {
print('No names supplied');
return;
}
for (final name in names) {
print(name.toUpperCase());
}
}
void main() {
printNames(null);
printNames(['Ada', 'Lin']);
}After the if statement returns, Dart promotes names from List<String>? to List<String> inside the remaining block. This lets the loop use the list safely.
For a nullable list, use ?. to perform an operation only when the list exists:
void main() {
final names = <String>?['Ada', 'Lin'];
print(names?.length); // 2
print(names?.first); // Ada
final count = names?.length ?? 0;
print(count); // 2
}The result of names?.length is int?, so ?? 0 converts it into a definite int.
Null-aware collection building
The null-aware spread operator, ...?, adds the elements of a nullable collection only when it is not null.
List<String> withGuest(List<String>? guests) {
return [
'Host',
...?guests,
];
}
void main() {
print(withGuest(null)); // [Host]
print(withGuest(['Guest 1', 'Guest 2'])); // [Host, Guest 1, Guest 2]
}This is useful when assembling UI data or request parameters from optional inputs.
Exercise
What are the types of map['key'] and List<String>??
Show answer
A map lookup is nullable because the key may be absent. List<String>? is a nullable list whose elements, when present, must be non-null strings.