Sub topic 2
Null Safety and Working with Collections
This chapter assumes you know Dart variables, functions, and generics such as List<int>. You should also understand nullable types such as int?.
Nullable lookups
A map lookup returns a nullable value, because the key may be missing. Use ?? to supply a default, or use ! when you are sure the key exists.
void main() {
final stock = <String, int>{'apple': 3, 'pear': 0};
final int? plums = stock['plum'];
print(plums ?? 0); // 0
final int apples = stock['apple']!; // safe: the key exists
print(apples); // 3
}Iterating with for-in and forEach
for-in and forEach work on any Iterable, which is the common interface shared by List, Set, and the results of where and map.
void main() {
final nums = [1, 2, 3];
for (final n in nums) {
print(n);
}
nums.forEach((n) => print(n * 2));
}Building collections with spread and control flow
The spread operator ... inserts the elements of one collection into another. The null-aware form ...? inserts nothing when the value is null. Collection if and for add elements conditionally or in a loop.
List<int> build(List<int> base, bool showExtra, List<int>? maybe) {
return [
0,
...base,
if (showExtra) 99,
for (final n in base) n * 10,
...?maybe,
];
}
void main() {
print(build([1, 2, 3], true, null)); // [0, 1, 2, 3, 99, 10, 20, 30]
print(build([1, 2, 3], false, [7])); // [0, 1, 2, 3, 10, 20, 30, 7]
}Transforming with where, map, fold, and toList
where and map are lazy: they do no work until toList or another terminal call runs them. fold reduces the collection to a single value.
void main() {
final nums = [5, 3, 8, 1, 9, 2];
final squares = nums.where((n) => n.isEven).map((n) => n * n).toList();
print(squares); // [64, 4]
final total = nums.fold<int>(0, (sum, n) => sum + n);
print(total); // 28
}Exercise
What does stock['kiwi'] ?? 0 evaluate to when the map stock has no 'kiwi' key?
Show answer
It evaluates to 0, because the lookup returns null and ?? supplies the default.
Q: What does [1, 2, ...?null] evaluate to?
A: It evaluates to [1, 2], because the null-aware spread inserts nothing.