Home > Software engineering >  Get Data from StreamSubscription in Flutter from Firestore
Get Data from StreamSubscription in Flutter from Firestore

Time:02-17

I'm implementing a leaderboard in my Flutter App.

This is how I set up the stream:

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

This is the result from my print:

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

Can I access data from there now? I found the documentation here: https://firebase.flutter.dev/docs/firestore/usage/

But there is not listed how I can get my data with this method.

CodePudding user response:

You can do:


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
   }

});

The snapshots call returns the Stream, now you need to listen to the stream.

The listen requires a callback on which you can capture the data being listened to.

  • Related