You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Contact类型的List中获取指定联系人的电话号码?

How to Retrieve John's Phone Number from Your Dart Contacts 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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:39:34