Dart:列表删除不删除对象

Dart: List remove not removing Object

如果您需要完整示例,代码在 DartPad 上(请参阅最后的 while 循环。)

我有一个循环,

Place place = places[0];
while (places.isNotEmpty) {
  // Get a list of places within distance (we can travel to)
  List reachables = place.getReachables();

  // Get the closest reachable place
  Place closest = place.getClosest(reachables);

  // Remove the current place (ultimately should terminate the loop)
  places.remove(place);

  // Iterate
  place = closest;
}

但它并没有删除倒数第二行的 place。即,places 列表的长度保持不变,使其成为一个无限循环。怎么了?

很可能 place 由于某种原因不在列表中。在不知道所使用的确切数据的情况下很难进行调试,问题不会在链接的 DartPad 中的三位示例中重现。

尝试找出导致问题的因素。例如你可以 尝试在删除之前添加一个 if (!places.contains(place)) print("!!! $place not in $places");,或类似的东西来检测问题发生时的状态。

这可能是因为列表中的对象与您要删除的对象具有不同的 hashCode。

尝试改用此代码,通过比较对象属性找到正确的对象,然后再删除它:

var item = list.firstWhere((x) => x.property1== myObj.property1 && x.property2== myObj.property2, orElse: () => null);

list.remove(item);

另一种选择是覆盖 class 中的 == 运算符和 hashCode。

class Class1 {
  @override
  bool operator==(other) {
    if(other is! Class1) {
      return false;
    }
    return property1 == (other as Class1).property1;
  }

  int _hashCode;
  @override
  int get hashCode {
    if(_hashCode == null) {
      _hashCode = property1.hashCode
    }
    return _hashCode;
  }
}

我也遇到过同样的问题。不幸的是我还没有找到根本原因,但在同样的情况下我更换了

places.remove[place]

places.removeWhere(p => p.hachCode == place.hashCode)

作为解决方法。另一种方法也很有帮助:

// Get the place from your set:
final place = places.first;
// Replace the place in the set:
places.add(place);
// Remove the place from the set:
places.remove(place);

这样您就可以从动态列表中删除对象

List data = [
    {
      "name":"stack"
    },
    {
      "name":"overflow"
    }
  ];
  
  data.removeWhere((item) => item["name"]=="stack");
  
  print(data);

Output

[{name: overflow}]