How to remove duplicates from list of objects in flutter

Viewed 1343

I have a list in my code that contains list of objects of contactsInfo such as

myContactsModel(
        displayName: 'Alex',
        phoneNumbers: '+4412318293',
        avatar: avatar)
myContactsModel(
        displayName: 'Alex',
        phoneNumbers: '+4412318293',
        avatar: avatar)

these objects are stored in a list .How to ensure that no duplicate item exists in the list having same name and number

4 Answers

You need to

  • override equality == operator,
  • which in turn requires overriding hashCode,
  • then use a Set to store unique items.

Sample Working Code

class ContactsModel {
  String displayName;
  String phoneNumbers;
  String avatar;
  ContactsModel(this.displayName, this.phoneNumbers, this.avatar);

  @override
  String toString() {
    return """
{
  'displayName': $displayName,
  'phoneNumbers': $phoneNumbers,
  'avatar': $avatar,
}""";
  }

  @override
  bool operator ==(other) {
    if (other is! ContactsModel) {
      return false;
    }
    return displayName == other.displayName &&
        phoneNumbers == other.phoneNumbers;
  }

  @override
  int get hashCode => (displayName + phoneNumbers).hashCode;
}

void main() {

  var models = <ContactsModel>{};

  models.add(
    ContactsModel('Alex', '+4412318293', 'avatar1'),
  );

  models.add(
    ContactsModel('Alex', '+4412318293', 'avatar1'),
  );

  print(models);
}

Output:

{{
  'displayName': Alex,
  'phoneNumbers': +4412318293,
  'avatar': avatar1,
}}

Try it in DartPad.

The informative answer here How does a set determine that two objects are equal in dart?.

Benson OO

I applied some basic logic of C&C++ And i got the results.!

i've created UserModel class,

class UserModel {
  final String? name;
  final String? phoneNo;

  UserModel({this.name, this.phoneNo});
}

Later on, I store 5 records in with different kind of data in userData named UserModel type list.

List<UserModel> userData = [
  UserModel(name: 'ABC', phoneNo: '1234567890'),
  UserModel(name: 'ABC', phoneNo: '1234567890'),
  UserModel(name: 'DEF', phoneNo: '1234567890'),
  UserModel(name: 'ABC', phoneNo: '1234567800'),
  UserModel(name: 'CBA', phoneNo: '0987654321'),
];

on Tap i created a method and run a loop to get unique records from userData,

for (int i = 0; i < userData.length; i++) {
  if (i < userData.length - 1) {
    if (userData[i].name != userData[i + 1].name ||
        userData[i].phoneNo != userData[i + 1].phoneNo) {
      sortedUserData.add(userData[i]);
    }
  } else {
    sortedUserData.add(userData[i]);
  }
}

And store output in sortedUserData named list.

Adding to @p2kr, you can use the shortcut

ctrl + enter

enter image description here

and override ==() and hashCode. From there, you can select all the fields you want compared. It will generate the code for you as needed.

After that you can simply do

var uniqueList = myContactsModel.toSet().toList();

List<Student> students = [
    Student(name: "John Cena", rollno: 3, dob: "2003-10-23"),
    Student(name: "John Cena", rollno: 4, dob: "2005-01-13"),
    Student(name: "Jack Sparrow", rollno: 6, dob: "1993-03-15"),
    Student(name: "Harry Potter", rollno: 3, dob: "2011-09-05"),
    Student(name: "Jack Sparrow", rollno: 4, dob: "1993-05-11"),
];


var seen = Set<String>();
List<Student> uniquelist = students.where((student) => seen.add(student.name)).toList();
//output list: John Cena, Jack Sparrow, Harry Potter

var seen = Set<String>();
List<Student> uniquelist = students.where((student) => seen.add(student.rollno.toString())).toList();
//output: John Cena (3), John Cena (4), Jack Sparrow (6)

Related