gpt4 book ai didi

firebase - 将Firebase文档快照映射到需要键和值并将其作为流提供的自定义模型

转载 作者:行者123 更新时间:2023-12-03 04:35:09 24 4
gpt4 key购买 nike

我正在尝试向小部件提供文档快照流,但是在此之前,我想将返回Map 的快照映射到自定义模型,以便该模型采用每个字段的键和值,将其传递给模型,然后根据快照文档中的几个字段创建所有UserInfo对象的列表

class DatabaseService {
final CollectionReference userCollection =
FirebaseFirestore.instance.collection('users');

final String uid;
DatabaseService({this.uid});

// the map function

List<UserInfo> _userInfo(DocumentSnapshot snapshot) {
//the line below is where i get the error that the expression has a type 'void' and it can't be used
snapshot.data().forEach((key, value) {
return UserInfo(key: key, value: value);
}).toList();
}

// The stream

Stream<List<UserInfo>> get userData {
return userCollection.doc(uid).snapshots().map(_userInfo);
}
这是模型UserInfo
class UserInfo {
final String key;
final dynamic value;

UserInfo({this.key, this.value});
}
我非常感谢能在这里获得的任何帮助。
我也非常清楚,我可以使用流构建器将流传递给窗口小部件,但是我试图使用这种方法。
谢谢

最佳答案

您需要使用map将可迭代(列表)转换为某种形式。 forEach不能用于此目的,因为它无法返回任何内容。

List<UserInfo> _userInfo(DocumentSnapshot snapshot) {
final data = snapshot.data();
return data.keys().map((key) {
return UserInfo(key: key, value: data[key]);
}).toList();
}

关于firebase - 将Firebase文档快照映射到需要键和值并将其作为流提供的自定义模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64293762/

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