Conditionally add to Map

655

Solution 1

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');
    }
  }
}

Solution 2

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);
}
Share:
655
user3808307
Author by

user3808307

Updated on December 27, 2022

Comments

  • user3808307
    user3808307 over 1 year

    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 }),
    };