1

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();
1
  • 1
    Use a Set instead of a List. And make sure your GetOrder model implements == and hashCode. Commented Jan 11, 2022 at 16:06

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.