从地图中删除元素

Removing elements from a Map

如何在地图上进行迭代,将元素逐一移除,然后在移除每个元素后调用一个函数?

假设我有释放功能

  final HashMap<int, bool> _instances = new HashMap<int, bool>();

  void release(dynamic instance) {
    if (_instances[instance.hashCode] != null) {
      _releaseHashCode(instance.hashCode);
      _dispatcher.dispatchEvent(PinEvent.release);
    }
  }

  void _releaseHashCode(int hashCode) => _instances.remove(hashCode);

现在我想创建 releaseAll(),它将为地图中的每个元素调用 _releaseHashCode,从而释放它并调度释放事件。

  void releaseAll() {
    ...
  }

我就是这样做的

  void releaseAll() {
    var tempMap = new HashMap<int, bool>()..addAll(_instances);
    tempMap.forEach((int hashCode, bool value) {
      _releaseHashCode(hashCode);
      _dispatcher.dispatchEvent(PinEvent.release);
    });
    tempMap.clear();
    tempMap = null;
  }

检查 removeWhere

final Map<String, dynamic> tempMap = json.decode(jsonValue);
tempMap.removeWhere((String key, dynamic value)=> value==null);