Reputation: 513
I'm trying to add object to a list only if it wasn't added already .. like this:
for (var interest in poll.poll.interests) {
InterestDrop n = new InterestDrop(interest, false);
print(interest);
print(dropInterestsList);
print(dropInterestsList.contains(n));
if (!(dropInterestsList.contains(n))){
dropInterestsList.add(n);
}
}
but this always return false and add the object even when its already there ... how to solve this?
ANSWER:
class InterestDrop {
String name;
bool isClicked;
InterestDrop(this.name, this.isClicked);
bool operator == (o) => o is InterestDrop && name == o.name && isClicked == o.isClicked;
int get hashCode => hash2(name.hashCode, isClicked.hashCode);
}
Upvotes: 1
Views: 163
Reputation: 3598
You need to do something like this:
class InterestDrop {
operator ==(InterestDrop other) => identifier == other.identifier;
}
Upvotes: 1
Reputation: 10861
You need to override the equality operator in your custom class.
From the docs:
The default behavior for all Objects is to return true if and only if this and other are the same object.
So your contains method will only return true if your array contains the exact object you are comparing against.
Upvotes: 2