如何在Dart中避免列表中的重复项?

4
我创建了一个ListView和一个Button,当我点击Button时,它会向ListView添加一个项目。
问题是我不想在列表中重复相同的项目。
我尝试过.contains方法,但它没有起作用。
请给我一个好的解决方案。
4个回答

6

有不同的方法来实现这一点:

1) 遍历列表并检查每个元素是否不具有您认为相等的属性:

items = [Item(id: 1), Item(id: 2)];
newItem = Item(id: 2);
if (items.every((item) => item.id != newItem.id)) {
  items.add(newItem);
}

2) 使用contains()方法并覆盖带有您认为相等的属性的对象类中的==运算符(同时也要覆盖hashCode方法)。

items = [Item(id: 1), Item(id: 2)];
newItem = Item(id: 2);
if (!items.contains(newItem)) {
  items.add(newItem);
}

// inside Item class
@override
bool operator ==(other) {
  return this.id == other.id;
}

@override
int get hashCode => id.hashCode;

3) 使用Set代替List,其中每个元素只能出现一次。它的默认实现是LinkedHashSet,可以跟踪顺序。


2

使用Set代替List。

void main() {
  Set<String> currencies = {'EUR', 'USD', 'JPY'};
  currencies.add('EUR');
  currencies.add('USD');
  currencies.add('INR');
  print(currencies);
}

输出:{EUR,USD,JPY,INR} // 仅唯一项

参考:Set<E>类


0
如果您的列表包含自定义对象,则可能需要覆盖自定义类中的相等运算符
您也可以使用Set而不是列表。

0
在添加元素之前,请检查列表是否已经包含该元素: https://api.flutter.dev/flutter/dart-core/List-class.html
if(!List.contains(element) { add }

contains 方法检查的是相等性而不是引用,它应该只要比较类似的元素就可以工作。如果您的代码无法正常工作,请将其提供给我们,谢谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接