Samoilov
Samoilov

Reputation: 578

How remove element duplicates in a list flutter

I am streaming api. With the API, I get 1 item each and add to the list. The fact is that the api stream works in a circle, and duplicates are added to the list. How can I eliminate duplicates?

Code add list:

groupData.map((dynamic item) => GetOrder.fromJson(item))
              .where((element) {
            if (element.orderId != null) {
              if (!list.contains(element)) {
                list.add(element);
              }
              return true;
            } else {
              return false;
            }
          }).toList();

Upvotes: 1

Views: 778

Answers (2)

Giovanni Londero
Giovanni Londero

Reputation: 1409

If elements are primitives, you can use a Set:

final myList = ['a', 'b', 'a'];
Set.from(myList).toList(); // == ['a', 'b']

but if elements are objects, a Set wouldn't work because every object is different from the others (unless you implement == and hashCode, but that goes beyond this answer)

class TestClass {
  final String id;
  
  TestClass(this.id);
}

...

final myClassList = [TestClass('a'), TestClass('b'), TestClass('a')];
Set.from(myClassList).toList(); // doesn't work! All classes are different

you should filter them, for example creating a map and getting its values:

class TestClass {
  final String id;
  
  TestClass(this.id);
}

...

final myClassList = [TestClass('a'), TestClass('b'), TestClass('a')];
final filteredClassList = myClassList
  .fold<Map<String, TestClass>>({}, (map, c) {
    map.putIfAbsent(c.id, () => c);

    return map;
  })
  .values
  .toList();

That said, this should work for you

groupData
  .map((dynamic item) => GetOrder.fromJson(item))
  .fold<Map<String, GetOrder>>({}, (map, element) {
    map.putIfAbsent(element.orderId, () => element);

    return map;
  })
  .values
  .toList();

Upvotes: 2

Karim
Karim

Reputation: 1010

You can use Set instead

A Set is an unordered List without duplicates

If this is not working, then chances are that u have different object for the same actual object. (meaning, you have in 2 different places in memory)

In this case .contains or Set will not work

Upvotes: 1

Related Questions