Flutter remove duplicates from list of objects

Flutter: Remove Duplicates from List of Objects

In Flutter, if you have a list of objects and you want to remove duplicates based on certain criteria, you can follow the steps below:

  1. Create a class for the object, let’s say MyObject, with all the necessary properties.
  2. Override the == and hashCode methods in the MyObject class based on the criteria you want to use for duplicate comparison.

    class MyObject {
      final int id;
      final String name;
      MyObject(this.id, this.name);
      bool operator ==(Object other) {
        if (identical(this, other)) return true;
        return other is MyObject && other.id == id && other.name == name;
      int get hashCode => id.hashCode ^ name.hashCode;

    In this example, we’re considering objects with the same id and name as duplicates.

  3. Create a list of objects, and you want to remove duplicates from this list.
    List objects = [
      MyObject(1, 'Apple'),
      MyObject(2, 'Banana'),
      MyObject(3, 'Apple'), // Duplicate
      MyObject(4, 'Orange'),
      MyObject(2, 'Banana'), // Duplicate
      MyObject(5, 'Grapes')
  4. To remove duplicates from the list, you can use the toSet() method to convert the list to a set, and then convert the set back to a list.

    List uniqueObjects = objects.toSet().toList();
  5. The uniqueObjects list will now contain the objects without any duplicates based on the criteria specified in the == and hashCode methods of MyObject class.

Leave a comment