【问题标题】:Flutter firestore get stream of document ids from a collectionFlutter firestore 从集合中获取文档 ID 流
【发布时间】:2021-12-16 10:17:50
【问题描述】:

我有下面的 Future 返回一个字符串列表,而不是我想返回具有相同文档 ID 列表的 Stream String List,我该怎么做?

Future<List<String>> getFollowingUidList(String uid) async{

final QuerySnapshot result = await FirebaseFirestore.instance.collection('following').doc(uid).collection('user_following').get();
final List<DocumentSnapshot> documents = result.docs;

List<String> followingList = [];

documents.forEach((snapshot) {
  followingList.add(snapshot.id);
});

return followingList;

}

【问题讨论】:

  • 而不是[...].get(),它返回一个Future,使用[...].snapshots(),它返回一个Stream
  • @pskink 如何从 Stream 流式传输文档 ID snapshots = FirebaseFirestore.instance.collection('following').doc(uid).collection('user_following').snapshots() ;
  • 你需要“修改”你原来的Stream,更多在这里:dart.dev/tutorials/language/streams#modify-stream-methods

标签: firebase flutter google-cloud-firestore


【解决方案1】:

根据 FlutterFire documentationCollectionReferencesnapshots() method 将返回一个 Stream。在 Dart 中,Streams 提供了一个 map() method,它允许您轻松地转换 Stream 并返回一个新的:

将此流的每个元素转换为一个新的流事件。 创建一个新流,使用 convert 函数将此流的每个元素转换为新值,并发出结果。

基于此,可以从 CollectionReference 的snapshots() Stream 返回一个带有文档 ID 的新 Stream。 CollectionReference 流的类型为QuerySnapshot,根据documentation,它包含typeList&lt;QueryDocumentSnapshot&gt;docs 属性。最后,此类型可以为您提供来自DocumentSnapshotsincluding 文档的ID 的data

Stream<List<String>> returnIDs() {
    return Firestore.instance
        .collection('testUsers')
        .snapshots()
        .map((querySnap) => querySnap.docs //Mapping Stream of CollectionReference to List<QueryDocumentSnapshot>
        .map((doc) => doc.data.id) //Getting each document ID from the data property of QueryDocumentSnapshot
        .toList());
 }

我在这个example 的基础上创建了这个 sn-p,它充满了有用的脚本,可以将 Streams 与 Firestore 结合使用。

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 2021-07-29
    • 2019-09-17
    • 2021-01-28
    • 2021-07-20
    • 1970-01-01
    • 2020-12-05
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多