Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates from list of objects in flutter

Tags:

flutter

dart

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

like image 944
Benson OO Avatar asked Sep 06 '25 03:09

Benson OO


2 Answers

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)

like image 120
Wicaledon Avatar answered Sep 07 '25 22:09

Wicaledon


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?.

like image 37
p2kr Avatar answered Sep 07 '25 22:09

p2kr