Null-aware operator with Maps

前端 未结 5 855
迷失自我
迷失自我 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 20:19

    Something like this might work as an extension function:

    extension MapExtensions on Map {
      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.

提交回复
热议问题