Null-aware operator with Maps

前端 未结 5 856
迷失自我
迷失自我 2020-12-18 19:42

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

相关标签:
5条回答
  • 2020-12-18 19:54

    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];
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-18 20:10

    This works:

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

    Because the key will fallback to accessing an empty Map, which will always return null.

    0 讨论(0)
  • 2020-12-18 20:17

    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.

    0 讨论(0)
  • 2020-12-18 20:19

    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.

    0 讨论(0)
提交回复
热议问题