首页 > 解决方案 > 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'
            );
          }

        }

提前致谢。

标签: firebasefluttergoogle-cloud-firestore

解决方案


您需要从文档快照中实际获取训练图,然后将其映射到列表流中,如下所示:

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']
  );
}

推荐阅读