Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add to Map

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 }),
};
like image 318
user3808307 Avatar asked Sep 02 '25 16:09

user3808307


2 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');
    }
  }
}
like image 176
Randal Schwartz Avatar answered Sep 05 '25 13:09

Randal Schwartz


You can do absolutely the same in Dart!

return {
   if (true) ...{'key': value},
};
like image 24
egorikem Avatar answered Sep 05 '25 13:09

egorikem