在Firestore中查询后如何获取集合中文档的名称?

时间:2020-03-28 00:19:07

标签: database firebase flutter google-cloud-firestore querying

我正在Flutter中编写一个应用程序,我希望能够根据特定条件查询Firestore中集合中的一组文档,然后使用符合所述条件的文档获取这些文档的名称。到目前为止,这是我尝试过的方法,但是没有用。

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

除了我称之为docRef.id的那部分之外,所有代码均有效。当我致电docRef.id时,出现错误消息:

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

1 个答案:

答案 0 :(得分:1)

执行查询时,在then回调中获得的结果是QuerySnapshot。即使只有一个符合条件的文档,您也会得到QuerySnapshot,其中只有一个文档。要获取作为结果的单个DocumentSnapshot,您需要遍历QuerySnapshot.documents

类似的东西:

Firestore.instance
    .collection('active')
    .where(topic, isEqualTo: true)
    .where('grade', isEqualTo: grade)
    .getDocuments()
    .then((querySnapshot) {
      querySnapshot.documens.forEach((doc) {
        print(doc.documentID)
      })
    });