如何从Contact类型的List中获取指定联系人的电话号码?
Great question! There are a few straightforward ways to get John's phone number from your List<Contact>. Let's break down the most common approaches:
1. Use firstWhere (Cleanest & Recommended)
The firstWhere method is perfect for this scenario—it finds the first element in the list that matches your condition. Here's how to use it:
// Locate the Contact object for John Contact john = contacts.firstWhere((contact) => contact.name == 'John'); // Extract the phone number int johnPhoneNumber = john.phoneNo; print(johnPhoneNumber); // Output: 2100 (note: leading zeros are stripped from integers)
2. Filter with where + first
If you prefer a more explicit filtering step, you can use where to get all contacts named "John" (though there's only one in your list) and then grab the first result:
Contact john = contacts.where((c) => c.name == 'John').first; int johnPhoneNumber = john.phoneNo;
3. Manual Loop (For Learning Purposes)
If you want to understand the underlying logic, you can loop through each contact and check the name directly:
int? johnPhoneNumber; // Use nullable int in case John isn't found for (var contact in contacts) { if (contact.name == 'John') { johnPhoneNumber = contact.phoneNo; break; // Stop looping once we find John } } if (johnPhoneNumber != null) { print(johnPhoneNumber); } else { print("John not found in contacts"); }
Critical Note About Phone Numbers as Integers
In your current code, phoneNo is stored as an int, but leading zeros (like the 00 in John's 002100) are lost because integers don't preserve leading zeros. If those leading zeros are important (which they often are for phone numbers), you should change the phoneNo type to String:
class Contact { String name; String email; String phoneNo; // Switch to String type Contact(this.name, this.email, this.phoneNo); } // Initialize with string phone numbers to keep leading zeros List<Contact> contacts = [ Contact('John', 'john@c.com', '002100'), Contact('Lily', 'lily@c.com', '083924'), Contact('Abby', 'abby@c.com', '103385'), ];
This way, when you retrieve John's phone number, it will stay as '002100' instead of being converted to 2100.
内容的提问来源于stack exchange,提问作者Blasanka

