I had the same problem with lists, now it is Map.
The following syntax is not Dart, as in it does not
I use this function for null-safe nested map access:
// Returns value of map[p1][p2]...[pn]
// where path = [p1, p2, ..., pn]
//
// example: mapGet(map, ["foo", 9, 'c'])
dynamic mapGet(Map map, List path) {
assert(path.length > 0);
var m = map ?? const {};
for (int i = 0; i < path.length - 1; i++) {
m = m[path[i]] ?? const {};
}
return m[path.last];
}
Yet another syntax I used a few times:
map?.containsKey(key) ?? false ? map[key] : otherValue
Although functionally equivalent to the one proposed by @Günter Zöchbauer it is a bit more cumbersome.
Anyway, since it might look clearer in a few circumstances, it is worth to mention.
This works:
(map ?? const {})[key] ?? otherValue;
Because the key
will fallback to accessing an empty Map
, which will always return null
.
Or
map != null ? map[key]: otherValue;
which checks to see if the map is null before attempting to access the variable, which is the same as Günter's answer but checks first.
Something like this might work as an extension function:
extension MapExtensions<T, K> on Map<T, K> {
K getOrNull(T key) {
if (this == null || !this.containsKey(key)) {
return null;
} else {
return this[key];
}
}
K getOrElse(T key, K fallback) {
return this.getOrNull(key) ?? fallback;
}
}
Note: I haven't tested this, but should work.