How to not duplicate same item in a list dart?

Viewed 4539

I have created a listView and button and when I click the button it adds an item to listView.

The problem is I don't want actually to repeat the same item in the list.

I've tried the .contains method but it didn't work.

I want a good solution please,

4 Answers

There are different ways to achieve this:

1) Iterate the list and check if every element doesn't have the properties you consider equal:

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

2) Use contains() and override == operator (and override hashCode too) in the object class with the properties you consider equal.

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) Instead of List use Set, where each element can occur only once. Its default implementation is LinkedHashSet that keeps track of the order.

Instead of List, Use Set.

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

output: {EUR, USD, JPY, INR} // unique items only

Reference: Set<E> class

Check if the List already contains the element before you add it: https://api.flutter.dev/flutter/dart-core/List-class.html

if(!List.contains(element) { add }

The contains method checks for equality, not for reference, so it must work as long as you compare a similar element. If your code isn't working, please provide it to us. Thanks.

If your list contains custom objects you may need to override the equality operator in the custom class.

You could also use a Set instead of a List.

Related