firebase - Flutter Firestore 从地图中获取每个条目的流
问题描述
我在 Firestore 中存储了一张地图。现在我想为这张地图中的每个条目(培训)接收一个流。有没有可能的方法来做到这一点。
也许像下面这样,但这里我的流只包含 1 个 Future,因为一个文档:
Stream<CalendarEvent> getTrainings() {
return _firestore
.collection('users')
.doc('${_authentication.getUID()}')
.collection('user')
.doc('trainings')
.snapshots()
.map((doc) => CalendarEvent.fromJson(doc.data()));
}
这是 CalendarEvent 的代码,其中使用工厂构造函数生成日历事件的实例,
class CalendarEvent {
final String title;
final String id;
final String date;
CalendarEvent({this.title, this.id, this.date});
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'title': title,
'id': id,
'date': date,
};
}
//Here we generate user object out of firestore
factory CalendarEvent.fromJson(Map<dynamic, dynamic> json) {
return CalendarEvent(
title: 'null',
id: 'null',
date:'null'
);
}
}
提前致谢。
解决方案
您需要从文档快照中实际获取训练图,然后将其映射到列表流中,如下所示:
Stream<List<CalendarEvent>> getTrainings() {
return _firestore
.collection('users')
.doc('${_authentication.getUID()}')
.collection('user')
.doc('trainings')
.snapshots()
.map((doc) {
Map<String, dynamic> trainingsMap = doc.data()['trainings'];
return trainingsMap.entries.map((mapEntry) {
Map<String, dynamic> json = {'id': mapEntry.key, ...mapEntry.value};
return CalendarEvent.fromJson(json);
}).toList();
});
}
并将您的 CalendarEvent.fromJson 更新为:
factory CalendarEvent.fromJson(Map<dynamic, dynamic> json) {
return CalendarEvent(
title: json['trainingsName'],
id: json['id'],
date: json['trainingsDate']
);
}
推荐阅读
- android-studio - Android工作室点击按钮崩溃西蒙说
- html - 如何使用 Cypress.io 检查重复数据?
- python - 如何从字符串中的同一位置提取数值(长度不同)?
- pandas - 熊猫插值没有给出我的预期
- python - 计算 fvt 表的 tf_idf
- swift - 通过函数设置内部时如何再次调用didSet?
- python - TypeError:“printBoardPG”对象不支持索引
- vba - 1 次迭代后仅弹出一次 MsgBox
- php - 如何在我的 Wordpress 博客中找到 custom.php 加载的 CSS 样式的来源?
- three.js - Three.js GLTF 材质更新不保留颜色