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
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)
You need to
==
operator,hashCode
,Set
to store unique items.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);
}
{{
'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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With