Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 检索满足条件的列表元素_Dart - Fatal编程技术网

Dart 检索满足条件的列表元素

Dart 检索满足条件的列表元素,dart,Dart,这是我的模型课: class Contact { String name; String email; int phoneNo; Contact(this.name, this.email, this.phoneNo); } 假设我有一个联系人列表,如下所示: List<Contact> contacts = [ new Contact('John', 'john@c.com', 002100), new Contact('Lily', 'lily@c.c

这是我的模型课:

class Contact {
  String name;
  String email;
  int phoneNo;

  Contact(this.name, this.email, this.phoneNo);
}
假设我有一个联系人列表,如下所示:

List<Contact> contacts = [
  new Contact('John', 'john@c.com', 002100),
  new Contact('Lily', 'lily@c.com', 083924),
  new Contact('Abby', 'abby@c.com', 103385),
];
列出联系人=[
新联系人('John','john@c.com', 002100),
新联系人('Lily','lily@c.com', 083924),
新联系人('Abby','abby@c.com', 103385),
];
我想从
联系人
列表
中获取
John的电话号码,我如何才能做到这一点?

这是我使用以下方法实现的:

singleWhere(布尔测试(E元素))→ E
返回单个元素 满足
测试

还有一些其他的方法。例如:

其中(布尔测试(E元素))→ Iterable
返回一个新的惰性Iterable 使用满足谓词
test
的所有元素

更新:

singleWhere()。如果存在重复项,将抛出
错误状态:元素太多


因此,根据@GunterZochbauer(参考他的答案)

singleWhere
的说法,最好的方法是
firstWhere
,如果存在重复项或没有匹配的元素,singleWhere将抛出

另一种选择是
firstWhere
orElse

“最好的一个”是相对的:它取决于你试图完成什么。如果你是100肯定的,那么列表必须只包含一个匹配的项,那么
singleWhere
是一个好主意,因为如果这个假设不成立,它会抛出一个异常-如果你基于这个假设构建代码,这表明一个严重的错误。另一方面,例如,如果您从某个不太可能遵循固定结构的云API获取一些JSON代码,那么
singleWhere
是有风险的,因为它可能会定期失败。
var urgentCont = contacts.singleWhere((e) => e.name == 'John');
print(urgentCont.phoneNo.toString().padLeft(6, '0'));//Output: 002100
var urgentCont = contacts.firstWhere((e) => e.name == 'John', orElse: () => null);
print(urgentCont?.phoneNo?.toString()?.padLeft(6, '0') ?? '(not found)');//Output: 002100