updateWith method
update element if key-value pair exists returned value is some.
remove element if key-value pair exists and returned value is null.
add element if key-value pair does not exist and returned value is some.
else it returns the as is.
In the example below,
if key
is not 'a','b' ,nor 'c', it returns {'a':1,'b':2,'c':3,'<key>':4,...}
if key
is 'a', it returns {'a': 100,'b':2,'c':3}
else it returns {'a': 1, 'b':2,'c': 3}
example
{'a':1,'b':2,'c':3}
.updateWith(key)((element) => element == null ? 4 : element == 1 ? element * 100 : null);
Implementation
Map<K, V> Function(V? Function(V?)) updateWith(K k) {
if (containsKey(k)) {
return (f) {
final clone = {...this};
final deleteIfNull = f(this[k]);
if (deleteIfNull == null) {
clone.remove(k);
return clone;
} else {
return {...this, k: deleteIfNull};
}
};
} else {
return (f) => f(null) == null ? this : <K, V>{...this, k: f(null)!};
}
}