Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not duplicate same item in a list dart?

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,

like image 399
the coder Avatar asked Sep 16 '25 07:09

the coder


1 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.

like image 129
Pablo Barrera Avatar answered Sep 17 '25 21:09

Pablo Barrera