I have the below user defined objects -
class PhoneBookContact {
String? phoneBookContact;
List<ContactNumber>? contactNumbers;
PhoneBookContact(this.phoneBookContact, this.contactNumbers);
}
class ContactNumber {
String phone;
bool availableOnBol;
ContactNumber(this.phone, this.availableOnBol);
}
In my main method I am creating a list for the ContactNumber class and then later adding that ContactNumber list to the contactNumbers property of PhoneBookContact list. This is all done inside of a for loop.
The issue I am having is when I am clearing the contactNumbers list after adding those items to the contactNumbers property of the PhoneBookContact list, I see those cleared from the PhoneBookContact list as well, which I find weird, or maybe I am not thinking it the right way.
List<PhoneBookContact> phoneBookContacts = [];
List<ContactNumber> contactNumbers = [];
for (var contact in contacts) {
contactNumbers.clear();
if (contact.phones.isNotEmpty) {
for (var phone in contact.phones) {
if (true) {
contactNumbers.add(ContactNumber(phone.number, true));
} else {
contactNumbers.add(ContactNumber(phone.number, false));
}
}
}
phoneBookContacts
.add(PhoneBookContact(contact.displayName, contactNumbers));
}
CodePudding user response:
Your PhoneBookContact constructor does not make a copy of the list. It takes a reference to the list and remembers it.
Since you clear the list every loop but reuse the same list instance, all your PhoneBookContacts will have the same list.
Lets clean up your method a little:
List<PhoneBookContact> phoneBookContacts = [];
for (var contact in contacts) {
List<ContactNumber> contactNumbers = [];
for (var phone in contact.phones) {
final condition = true; // should be your complicated expression
contactNumbers.add(ContactNumber(phone.number, condition));
}
phoneBookContacts.add(PhoneBookContact(contact.displayName, contactNumbers));
}
Apart from removing some clutter, it makes sure that each loop, you instantiate a new list so that each PhoneBookContact has it's own list.