Search code examples
flutterdartgoogle-cloud-firestorestream

Get a single document from Firebase Firestore query with Flutter


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!


Solution

  • 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;
                }
              },
            );
      }