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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With