gpt4 book ai didi

flutter - 如何从列表中获取特定数据

转载 作者:IT王子 更新时间:2023-10-29 07:08:52 25 4
gpt4 key购买 nike

我有一个方法可以从 firebase 数据库中获取所有用户,然后将所有用户存储在一个列表中。假设我的 list 是:

    user1 = User(
id: 1
name: "john"
car: false
)

user2 = User(
id: 2
name: "kim"
car: true
)

userList = [user1,user2]

如何根据名称获取用户 ID?

最佳答案

最简单的方法之一是使用 forEach(),它需要一个函数作为参数:

class User{
final int id;
final String name;
final bool car;

User({this.id, this.name, this.car});
}

void main() {
User user1 = User(
id: 1,
name: "john",
car: false
);

User user2 = User(
id: 2,
name: "kim",
car: true
);

List<User> userList = [user1,user2];

userList.forEach((user){
if(user.name == "john")
print("ID: ${user.id}");
});
}

但您还有更多选择,请查看此列表 Top 10 Array utility methods you should know (Dart)

这样你就可以得到所有的约翰:

List<User> johns = userList.where((user) => user.name == "jhon");

关于flutter - 如何从列表中获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57656610/

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