从 Firestore 的 Flutter 中从 StreamSubscription 获取数据

Get Data from StreamSubscription in Flutter from Firestore

我正在我的 Flutter 应用程序中实现排行榜。

这是我设置流的方式:

Stream collectionStream = FirebaseFirestore.instance.collection('leaderboard').snapshots();
print(collectionStream.listen);

这是我打印的结果:

I/flutter (17212): Closure: (((QuerySnapshot<Map<String, dynamic>>) => void)?, {Function? onError, (() => void)? onDone, bool? cancelOnError}) => StreamSubscription<QuerySnapshot<Map<String, dynamic>>> from Function 'listen':.

我现在可以从那里访问数据吗? 我在这里找到了文档:https://firebase.flutter.dev/docs/firestore/usage/

但是没有列出如何使用此方法获取数据。

你可以这样做:


FirebaseFirestore.instance.collection('leaderboard').snapshots()
.listen((QuerySnapshot collection) {
   // consume the collection being streamed / listened to
   for (var doc in collection.docs) {
      var docData = doc.data() as Map<String, dynamic>;
      // do what you want with your data here
   }

});

快照调用returns流,现在你需要收听流。

listen 需要一个回调,您可以在回调中捕获正在收听的数据。