Search code examples
flutterdartstream-builder

Getting QuerySnapshot instead of DocumentSnapshot [FLUTTER]


StreamBuilder(
         stream: FirebaseFirestore.instance.collection('users').snapshots(),
         builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
           if (!snapshot.hasData) {
             return CircularProgressIndicator();
           }
           FirestoreUser firestoreUser =
               FirestoreUser.fromDocument(snapshot.data); // Here snapshot.data is retrieving QuerySnapshot.
               // How I can convert it to DocumentSnapshot 
          ...

Hello StackOverflow users

I need to give to my new firestoreUser variable, which type of DocumentSnapshot. But I can't get it.

After writing snapshot.data it gives me an error called "QuerySnapshot is not subtype of DocumentSnapshot"

P.s I'm using StreamBuilder as you can see. Thank you


Solution

  • Your stream is FirebaseFirestore.instance.collection('users').snapshots() which is a QuerySnapshot, meaning, a List of QueryDocumentSnapshot which Extends DocumentSnapshot. So if you want the documentSnapshot of every users in your 'users' collection, you will have to iterate over snapshot.data.docs: But if you want to get the document of a particular user, then you can do:

    StreamBuilder(
             stream: FirebaseFirestore.instance.collection('users').doc(userID).snapshots(),
             builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
               if (!snapshot.hasData) {
                 return CircularProgressIndicator();
               }
               FirestoreUser firestoreUser =
                   FirestoreUser.fromDocument(snapshot.data); 
              ...