putIfAbsent 方法

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

    查找key的值,如果不存在则添加新条目。

    如果有与key关联的值,则返回该值。如果没有,则调用ifAbsent以获取新值,将key关联到该新值,然后返回该新值。

    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}
    

    调用ifAbsent时不应从映射中添加或删除键。

    实现

    dynamic putIfAbsent(String key, dynamic ifAbsent()) {
      throw new UnsupportedError("Not supported");
    }