Dart:列表删除不删除对象

Gan*_*ede 7 dart

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

我有一个循环,

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;
}
Run Code Online (Sandbox Code Playgroud)

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

liv*_*ove 5

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

尝试使用此代码,在删除之前通过比较对象属性来找到正确的对象:

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

list.remove(item);
Run Code Online (Sandbox Code Playgroud)

另一种选择是覆盖类中的 == 运算符和 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;
  }
}
Run Code Online (Sandbox Code Playgroud)


lrn*_*lrn 0

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

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