Get a single document from Firebase Firestore query with Flutter

Andres Silva picture Andres Silva · Jun 21, 2020 · Viewed 7.6k times · Source

I know this might seem obvious, but I just can't find a way to do it..

I am trying to get a single document from a firebase query. When I say a single document I mean not a stream.

My approach so far is:

MyClass getDocument(String myQueryString) {
    return Firestore.instance.collection('myCollection').where("someField", isEqualTo: myQueryString) //This will almost certainly return only one document
        .snapshots().listen(
            (querySnapshot) => _myClassFromSnapshot(querySnapshot.documents[0])
    );
  }

However, I am getting the error A value of type 'StreamSubscription<QuerySnapshot>' can't be returned from method 'getDocument' because it has a return type of 'MyClass'.

Thanks!

Answer

Andres Silva picture Andres Silva · Jun 21, 2020

Thanks for your replies,

I finally got it to work by doing this:

Future<MyClass> getDocument(String myQueryString) {
    return Firestore.instance.collection('myCollection')
        .where("someField", isEqualTo: myQueryString)
        .limit(1)
        .getDocuments()
        .then((value) {
            if(value.documents.length > 0){
              return _myClassFromSnapshot(value.documents[0]);
            } else {
              return null;
            }
          },
        );
  }