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
CodePudding user response:
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?.
CodePudding user response:
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.