我正在使用 Riverpod 的 StreamProvider 从 Firestore 中获取一个包含数组的字段,然后将其映射到一个类,如下所示。
final firebaseFollowingProvider = StreamProvider<List<Following>>((ref) {
final stream = FirebaseFirestore.instance.collection('following').doc('d48391af-380d-4377-a3f9-d38cf5af7923').snapshots();
return stream.map((snapshot) => snapshot.data()!.map((doc) => Following.fromDocument(doc)).toList());
});
我的模型看起来像这样
class Following {
dynamic following;
Following({this.following});
Following.fromJson(Map<String, dynamic> json)
: following = json['isFollowing'];
Map<String, dynamic> toJson() => {
'isFollowing': following,
};
factory Following.fromDocument(DocumentSnapshot doc) {
return Following(following: doc['isFollowing']);
}
}
我得到的错误是
<块引用>无法分配参数类型 'MapEntry<_, > Function(String)'
到参数类型 'MapEntry
既然 snapshot.data()
已经返回了一个 Map,那么如何将 StreamProvider 返回的数据映射到一个类?
我正在使用 cloud_firestore: ^2.3.0
非常感谢。
答案 0 :(得分:0)
不要在模型类中将变量定义为 dynamic
。模型类旨在为您提供类型安全性,而 dynamic
变量会避开类型系统。
这样会更好(还没有测试过):
class Following {
final String following;
Following({required this.following});
Following.fromJson(Map<String, dynamic> json)
: following = json['isFollowing'] as String;
Map<String, dynamic> toJson() => {
'isFollowing': following,
};
factory Following.fromDocument(DocumentSnapshot doc) {
return Following(following: doc['isFollowing'] as String);
}
}
答案 1 :(得分:0)
问题是我返回了一个以下类型的列表,即 <List<Following>>
而不是返回 Following
final firebaseFollowingProvider = StreamProvider.autoDispose<Following>((ref) {
final stream = followingRef.doc('d48391af-380d-4377-a3f9-d38cf5af7923').snapshots();
return stream.map((snapshot) => Following.fromDocument(snapshot));
});