Florian Würmseer
Florian Würmseer

Reputation: 13

Dart Stream / List

I want to add a User into my List if there is no user with that name yet. Actually I generally want to avoid duplicates. As I didn't find something like myList.distinct(User.name) or something like that I did it with a for for loop and if else:

myList.add(customUser);
for (User user in myList) {
  if (user.name == customUser.name)
    myList.remove(user);
}

I was just wondering if there is a smarter way to solve this in dart for example with a stream. But I didn't find anything.

Upvotes: 0

Views: 333

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657018

You can use a Set instead of a list. A set only stores unique values.

For this if your values are custom class instances (User), your User class needs to implement operator == for a Set to work properly.

For more details see How does a set determine that two objects are equal in dart?

Upvotes: 2

Related Questions