1

I am programming an app in Flutter and I want to be able to query a set of documents in a collection in Firestore based on specific criteria and then with the documents that fit said criteria get the name of those documents. This is what I have tried so far however it does not work.

 getDoc(String topic, int grade) {
  return Firestore.instance
    .collection('active')
    .where(topic, isEqualTo: true)
    .where('grade', isEqualTo: grade)
    .getDocuments()
    .then((docRef) {
      return docRef.id;
    });
  }

All of the code works except for the part where I call docRef.id. When I call docRef.id I get an error saying:

The getter 'id' isn't defined for the class 'QuerySnapshot'.
Try importing the library that defines 'id', correcting the name to the name of an existing getter, or defining a getter or field named 'id'.d
Hudson Kim
  • 416
  • 6
  • 15
  • `docRef` is not actually a DocumentReference. The error message is telling you that it's a QuerySnapshot. You have to iterate the document snapshots in it to find out about them. – Doug Stevenson Mar 28 '20 at 00:36

1 Answers1

1

When you perform a query, the result you get in your then callback is a QuerySnapshot. Even if there's only one document matching the conditions, you'll get a QuerySnapshot with a single document in there. To get the individual DocumentSnapshot that are the result, you'll want to loop over the QuerySnapshot.documents.

Something like:

Firestore.instance
    .collection('active')
    .where(topic, isEqualTo: true)
    .where('grade', isEqualTo: grade)
    .getDocuments()
    .then((querySnapshot) {
      querySnapshot.documens.forEach((doc) {
        print(doc.documentID)
      })
    });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807