putIfAbsent method

  1. @override
V putIfAbsent(
  1. K key,
  2. _IfAbsent<V> ifAbsent, {
  3. bool notifyListeners = true,
})
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.

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}

Calling ifAbsent must not add or remove keys from the map.

Implementation

@override
V putIfAbsent(K key, _IfAbsent<V> ifAbsent, {bool notifyListeners = true}) {
  if (!value.containsKey(key)) {
    value.putIfAbsent(key, ifAbsent);
    if (notifyListeners) {
      notifyAllListeners(CollectionEventType.addition, key, value[key]!);
    }
  }

  return value[key]!;
}