Conditionally add to Map

Viewed 1137

I have a Map to which I would like add elements only if they meet a condition.

For example, if for keys a and b, is there something that works like this?

Map myMap = {
  if a is not null "a" : a,
  if b is not null and be is not empty "b": b,
}

So a and b would not be in the map unless the condition is met

For example for react is goes something like this

const myMap = {
  ...(a != null && { a: a }),
  ...(b != null && b.length > 0 && { b: b }),
};
3 Answers

Try this in dartpad:

void main() {
  for (var a in [null, 15]) {
    for (var b in [null, '', 'hello']) {
      var myMap = {
        if (a != null) 'a': a,
        if (b != null && b.isNotEmpty) 'b': b,
      };

      print('a = $a, b = $b, myMap = $myMap');
    }
  }
}

Dartpad is very useful

   void main() {
    Map<String, String> myMap = new Map();    
    Map<String,String> array = {"a":"apple","b":"g"}; 

    array.forEach((key,value){ 
     value.length> 0 ? myMap.addAll({key: value}): "";
    });
    print(myMap);
}

You can do absolutely the same in Dart!

return {
   if (true) ...{'key': value},
};
Related