Null-aware operator with Maps

2020-02-13 12:16发布

问题:

I had the same problem with lists, now it is Map.

What I would like to do

The following syntax is not Dart, as in it does not compile:

map?[key] ?? otherValue

If my map was not a Map but a List, it would look like Günter pointed out here:

list?.elementAt(index) ?? otherValue

What I am searching for

I understand that map?[key] is not valid syntax and therefore I am searching for something like elementAt, which works for lists, for maps.

map?.valueFor(key) ?? otherValue

valueOf

That does obviously not yet exist. The problem has solutions and valueOf might be a good one as well.

回答1:

This works:

(map ?? const {})[key] ?? otherValue;

Because the key will access an emtpy Map, which will always return null.



回答2:

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.



回答3:

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];
}


标签: dart