ensureKey method

void ensureKey(
  1. K key,
  2. V value
)

Ensure that the map contains the key. If not, add it with the value to prevent null or overriding values.

Example:

final map = {'a': 1, 'b': 2, 'c': 3};
map.ensureKey('d', 4);
print(map); // Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

// If the [key] already exists, its value will not be overridden.
final map = {'a': 1, 'b': 2, 'c': 3};
map.ensureKey('b', 4);
print(map); // Output: {'a': 1, 'b': 2, 'c': 3}

Implementation

void ensureKey(K key, V value) {
  if (!containsKey(key)) {
    this[key] = value;
  }
}