How to not duplicate same item in a list dart?
Solution 1
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.
Solution 2
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
the coder
Updated on December 15, 2022Comments
-
the coder over 1 year
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,