【问题标题】:Dart: List remove not removing ObjectDart:列表删除不删除对象
【发布时间】:2015-12-18 06:45:59
【问题描述】:

如果您需要一个完整的示例,代码在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 列表的长度保持不变,使其成为无限循环。怎么了?

【问题讨论】:

标签: dart


【解决方案1】:

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

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);

【讨论】:

【解决方案2】:

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

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

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

list.remove(item);

另一种选择是在您的类中覆盖 == 运算符和 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;
  }
}

【讨论】:

【解决方案3】:

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

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

【讨论】:

  • place = places[0]; while(...) { places.remove(place); } [错误] 让我感到困惑。我没有从places 列表中删除其他任何地方。我确定这是我的代码中的一个错误,我会继续修改它。
  • 你可以试试这个答案:) stackoverflow.com/a/70569910/12121284
【解决方案4】:

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

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

输出

[{name: overflow}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 2020-04-17
    • 1970-01-01
    • 2019-08-10
    • 2014-05-26
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多