putIfAbsent method

String putIfAbsent(
  1. String key,
  2. String ifAbsent()
)
override

Look up the value of key, or add a new entry if it isn't there.

Returns the value associated to key, if there is one. Otherwise calls ifAbsent to get a new value, associates key to that value, and then returns the new value.

That is, if the key is currently in the map, map.putIfAbsent(key, ifAbsent) is equivalent to map[key]. If the key is not currently in the map, it's instead equivalent to map[key] = ifAbsent() (but without any guarantee that the [] and []= operators are actually called to achieve that effect).

final diameters = <num, String>{1.0: 'Earth'};
final otherDiameters = <double, String>{0.383: 'Mercury', 0.949: 'Venus'};

for (final item in otherDiameters.entries) {
  diameters.putIfAbsent(item.key, () => item.value);
}
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}

// If the key already exists, the current value is returned.
final result = diameters.putIfAbsent(0.383, () => 'Random');
print(result); // Mercury
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}

The ifAbsent function is allowed to modify the map, and if so, it behaves the same as the equivalent map[key] = ifAbsent().

Implementation

String putIfAbsent(String key, String ifAbsent()) {
  if (!containsKey(key)) this[key] = ifAbsent();
  return this[key] as String;
}