What is map.putIfAbsent() in Dart?

The putIfAbsent() method

In Dart, the putIfAbsent() method checks the value of key or creates one if it doesn’t exist.

Syntax


V putIfAbsent (K key, V ifAbsent())

Parameters and return value

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.

Code

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

Explanation

  • 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.

Free Resources