【问题标题】:Flutter Firestore - How to get data from a Document Reference in a Document Field?Flutter Firestore - 如何从文档字段中的文档引用中获取数据?
【发布时间】:2021-10-27 04:46:00
【问题描述】:

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

在 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);
  });
});

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

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

提前感谢您的支持!

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    有没有办法告诉 firestore.instance 从那些 自动引用?还是我需要为每个 一个?

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

    要构建引用,请使用doc() 方法

    DocumentReference docRef = FirebaseFirestore.instance.doc("cards/WzU...");
    

    然后在这个DocumentReference上使用get()方法。

    docRef
    .get()
    .then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        print('Document exists on the database');
      }
    });
    

    具体来说,您可以遍历cards 数组并将get() 方法返回的所有Futures 传递给“等待多个futures 完成并收集它们的结果”的wait() 方法。有关更多详细信息,请参阅此SO answer,并注意“返回的未来的值将是通过迭代期货按照提供期货的顺序生成的所有值的列表。”

    【讨论】:

    猜你喜欢
    • 2019-11-27
    • 2020-12-05
    • 1970-01-01
    • 2020-12-03
    • 2022-01-20
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2020-08-01
    相关资源
    最近更新 更多