putIfAbsent()
methodIn Dart, the putIfAbsent()
method checks the value of key
or creates one if it doesn’t exist.
V putIfAbsent (K key, V ifAbsent())
If there is a value associated with key
, it is returned. Otherwise, it uses ifAbsent()
to get a new value, associates key
with it, and returns the new value.
void main() {Map<String, int> age = {'Eva': 16};print('The orignal map: ${age}');for (var key in ['Tobby', 'Eddie', 'Maria']) {age.putIfAbsent(key, () => key.length * 2);}print('The new map:${age}');}
In the code above, we create a map named age
.
Next, we use the for
loop to iterate over the iterable and pass the putIfAbsent
method, which returns the value associated to key
, if there is one.
Otherwise, it calls ifAbsent
to get a new value, associates key
with it, and returns the new value.