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 }),
};
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');
}
}
}
You can do absolutely the same in Dart!
return {
if (true) ...{'key': value},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With