Flutter Firestore - 如何从文档字段中的文档引用获取数据?

Jeo*_*oxs 7 firebase google-cloud-platform flutter google-cloud-firestore

我正在构建一个具有不同问题类型的自学应用程序。现在,其中一个问题有一个包含文档参考列表的字段:

在此输入图像描述

在 Flutter 中,我有以下代码:

Query<Map<String, dynamic>> questionsRef = firestore
.collection('questions')
.where('lesson_id', isEqualTo: lessonId);

await questionsRef.get().then((snapshot) {
  snapshot.docs.forEach((document) {
    var questionTemp;
    switch (document.data()['question_type']) {


      ....



      case 'cards':
        questionTemp = CardsQuestionModel.fromJson(document.data());
        break;


      ....


    }
    questionTemp.id = document.id;
    questions.add(questionTemp);
  });
});
Run Code Online (Sandbox Code Playgroud)

现在,通过“questionTemp”,我可以访问所有字段(lesson_id、options、question_type 等),但是当涉及“cards”字段时,我如何访问该文档引用中的数据?

有没有办法告诉 firestore.instance 自动从这些引用中获取数据?或者我需要为每个电话重新拨打电话吗?如果是这样,我该怎么做?

感谢您提前的支持!

Ren*_*nec 7

有没有办法告诉 firestore.instance 自动从这些引用中获取数据?或者我需要为每个电话重新拨打电话吗?

不,没有任何方法可以自动获取这些文档。您需要为每个数组元素构建相应的DocumentReference并获取文档。

要构建参考,请使用以下doc()方法

DocumentReference docRef = FirebaseFirestore.instance.doc("cards/WzU...");
Run Code Online (Sandbox Code Playgroud)

然后使用get()this 上的方法DocumentReference

docRef
.get()
.then((DocumentSnapshot documentSnapshot) {
  if (documentSnapshot.exists) {
    print('Document exists on the database');
  }
});
Run Code Online (Sandbox Code Playgroud)

具体来说,您可以循环遍历数组,并将该方法cards返回的所有 Future 传递给“等待多个 future 完成并收集其结果”的方法。有关更多详细信息,请参阅此SO 答案,并请注意“返回的 future 的值将是按照迭代 future 提供 future 的顺序生成的所有值的列表。”get()wait()