update 方法

V update(
  1. K key,
  2. V update(
    1. V value
    ), {
  3. V ifAbsent()?,
})
override

更新提供的 key 的值。

返回与键关联的新值。

如果键存在,则使用当前值调用 update,并将新值存储在映射中。

如果键不存在且提供了 ifAbsent,则调用 ifAbsent,并将返回的值与键一起添加到映射中。

如果键不存在,必须提供 ifAbsent

final planetsFromSun = <int, String>{1: 'Mercury', 2: 'unknown',
  3: 'Earth'};
// Update value for known key value 2.
planetsFromSun.update(2, (value) => 'Venus');
print(planetsFromSun); // {1: Mercury, 2: Venus, 3: Earth}

final largestPlanets = <int, String>{1: 'Jupiter', 2: 'Saturn',
  3: 'Neptune'};
// Key value 8 is missing from list, add it using [ifAbsent].
largestPlanets.update(8, (value) => 'New', ifAbsent: () => 'Mercury');
print(largestPlanets); // {1: Jupiter, 2: Saturn, 3: Neptune, 8: Mercury}

实现

V update(K key, V update(V value), {V Function()? ifAbsent}) {
  var comp = _splay(key);
  if (comp == 0) {
    var modificationCount = _modificationCount;
    var splayCount = _splayCount;
    var newValue = update(_root!.value);
    if (modificationCount != _modificationCount) {
      throw ConcurrentModificationError(this);
    }
    if (splayCount != _splayCount) {
      _splay(key);
    }
    _root = _root!._replaceValue(newValue);
    _splayCount += 1;
    return newValue;
  }
  if (ifAbsent != null) {
    var modificationCount = _modificationCount;
    var splayCount = _splayCount;
    var newValue = ifAbsent();
    if (modificationCount != _modificationCount) {
      throw ConcurrentModificationError(this);
    }
    if (splayCount != _splayCount) {
      comp = _splay(key);
    }
    _addNewRoot(_SplayTreeMapNode(key, newValue), comp);
    return newValue;
  }
  throw ArgumentError.value(key, "key", "Key not in map.");
}