3

I have a list of constructed objects called RecentCard which is basically an object with user id, pic, and name. I have created a list arranged in order of most recent interaction based on timestamp. However i need to get rid of the second occurence and onwards of any duplicated object. I am comparing just the ids since users may have the same name or photo, and i cannot remove duplicates from a simple list of uids because then i could lose the order of corresponding photos and names.

For example the list would look something like this :

List<RecentCard> recentCards= [RecentCard(uid:as721dn18j2,name:mike,photourl:https://sadadasd1d1),RecentCard(.....]

I have searched for solutions but all of them are dealing with like primitive types like simple lists of strings and the solutions didn't work for me. For example this post: How to delete duplicates in a dart List? list.distinct()? Read below

The first answer's link is no longer available, the next answer with sets is something i tried but it simply doesnt work i have no idea why maybe because its not a primitive type. The next answer with the queries package didn't work because i was using the list to build a listview.builder and so when i called list.length it said i couldnt call that on an iterable or something. The final solution wouldn't work because it said String is not a subtype of RecentCard.

I tried using two forloops with the second just comparing first value to the next couple but that doesnt work because if a duplicate is found, the object is removed and the length is messed up so some elements get skipped.

Any ideas? I feel like its very simple but im not sure how to do it.

Potato
  • 509
  • 1
  • 6
  • 17

1 Answers1

3

You have to use Set to store seen cards and then filter away those ones that are already in the set.

final seenCards = Set<String>();
final uniqueCards = recentCards.where((card) => seenCards.add(card.uid)).toList();
Niko Ruotsalainen
  • 49,514
  • 4
  • 24
  • 31