gpt4 book ai didi

dart - 检索满足条件的列表元素

转载 作者:行者123 更新时间:2023-12-03 02:48:39 26 4
gpt4 key购买 nike

这是我的模型类:

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来自 contacts 的电话号码 List , 我怎样才能做到这一点?

最佳答案

singleWhere如果有重复或没有匹配的元素,则抛出。

另一种选择是 firstWhereorElse https://api.dartlang.org/stable/1.24.3/dart-core/Iterable/firstWhere.html

var urgentCont = contacts.firstWhere((e) => e.name == 'John', orElse: () => null);
print(urgentCont?.phoneNo?.toString()?.padLeft(6, '0') ?? '(not found)');//Output: 002100

关于dart - 检索满足条件的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50522998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com