【问题标题】:Flutter / Dart / Firebase - Stream returning empty listFlutter / Dart / Firebase - 流返回空列表
【发布时间】:2020-03-21 13:29:15
【问题描述】:

我遇到了一个问题,将 Stream 返回到 StreamBuilder 小部件中。我正在尝试访问一个自定义类,该类存储为我在 firebase 中的用户集合中的列表,但由于某种原因,它继续返回一个空列表。

这是我的PhotoEntry 自定义类的示例:

class PhotoEntry {
  final Timestamp date;
  final String fileUrl;

  PhotoEntry({
    @required this.date,
    @required this.fileUrl,
  });

  Map<String, dynamic> toMap() => {
        'date': date.millisecondsSinceEpoch,
        'fileUrl': fileUrl,
      };

  PhotoEntry.fromMap(Map<String, dynamic> data)
      : date = new Timestamp.fromMillisecondsSinceEpoch(data['date']),
        fileUrl = data['fileUrl'];

  PhotoEntry.initial()
      : date = Timestamp.now(),
        fileUrl = 'No Photo';
}

这是给我带来麻烦的 Stream。正如我所说,它返回一个空列表:

Stream<List<PhotoEntry>> getUserPhotosStream(User user) {
    if (user == null) {
      return Stream.empty();
    }
    try {
      return _db
          .collection('users')
          .document(user.uid)
          .collection('photos')
          .snapshots()
          .map((list) => list.documents
              .map((doc) => PhotoEntry.fromMap(doc.data))
              .toList());
    } catch (e) {
      print(e);
      rethrow;
    }
  }

这里使用getUserPhotosStream

  Widget _galleryPage() {
    return StreamBuilder<List<PhotoEntry>>(
      stream: _db.getUserPhotosStream(_user),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting ||
            !snapshot.hasData) {
          return Container(child: Center(child: CircularProgressIndicator()));
        } else {
          return ListView.builder(
            scrollDirection: Axis.horizontal,
            physics: BouncingScrollPhysics(),
            itemCount: _user.photos.length,
            itemBuilder: (context, index) {
              var photo = snapshot; // For debugging
              print(photo); // For dubigging

              // return Card(photo)
            },
          );
        }
      },
    );
  }

我已经验证了集合和文档标题是正确的,并且传入的用户不为空并且包含所有正确的数据。我在这里做错了什么?

【问题讨论】:

  • so PhotoEntry.fromMap 被多次调用,但你有一个空列表?
  • @pskink PhotoEntry.fromMap 仅在将我的地图转换为列表时被调用一次。但是,是的,这是一个空列表。
  • 你在哪里使用getUserPhotosStream方法?发布您的StreamBuilder的代码
  • @pskink 编辑了我的原始帖子以包含StreamBuilder
  • 似乎itemCount: _user.photos.length 不正确-您必须根据snaphot.data 获得计数

标签: firebase flutter dart google-cloud-firestore stream


【解决方案1】:

我遇到过类似的情况,不确定这是否正是您的情况,但我的回答可以帮助面临空列表问题的人。就我而言,其中有一个 users 集合,其中有一个 doctors 集合,其中包含他们的 messages 集合。 my messages collection

我通过 firebase 仪表板手动添加了一个医生对象作为字段,因此 firebase 无法访问它的集合,并且总是返回空列表。下图可能有助于更好地理解: the right way to add dummy data

【讨论】:

    猜你喜欢
    • 2021-03-10
    • 2020-11-10
    • 2022-12-18
    • 2019-12-20
    • 2021-08-12
    • 1970-01-01
    • 2020-08-31
    • 2021-06-07
    • 2020-05-15
    相关资源
    最近更新 更多