【问题标题】:Unable to return list from Firebase Firestore In Flutter无法从 Flutter 中的 Firebase Firestore 返回列表
【发布时间】:2021-12-27 20:35:06
【问题描述】:

我目前正在开发 Flutter 中的测验应用程序。我正在从 firebase 获取数据并成功创建了包含我所需数据的地图列表。

但问题是我在 snapshot.docs 上执行 forEach 循环并将值添加到空的 AllQuestionsOfQuiz 列表中,但我无法从函数中返回它。

我不知道我在这里缺少的是代码:

import 'dart:convert';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:kbc/screen/question.dart';

class QuizCreator {

static List AllQuestionsOfQuiz = [];

  static Future<List<String>> fetchOptions(
      QueryDocumentSnapshot<Map<String, dynamic>> questionSnap) async {
    List<String> queOptions = [];
    await questionSnap.reference
        .collection("options")
        .get()
        .then((value) async {
      value.docs.forEach((element) {
        queOptions.add(element.data()["opt1"]);
        queOptions.add(element.data()["opt2"]);
        queOptions.add(element.data()["opt3"]);
        queOptions.add(element.data()["opt4"]);
      });
    });
    return queOptions;
  }

  static Future<Map> fetchQuestion(
      QueryDocumentSnapshot<Map<String, dynamic>> questionSnap,
      String QuePrize) async {
    Map questionNOpt = {};
    String question;
    await questionSnap.reference
        .collection("questions")
        .get()
        .then((value) async {
      question = value.docs.elementAt(0)["question"];
      questionNOpt["prize"] = QuePrize;
      questionNOpt["question"] = question;
      questionNOpt["options"] = await fetchOptions(value.docs.elementAt(0));
    });
    return questionNOpt;
  }

  static Future<List> quizCreator(String quizID) async {
 List QuestionOfQuizzes = [];
    await FirebaseFirestore.instance
        .collection("quizzes")
        .doc(quizID)
        .collection("prizes")
        .orderBy("prize", descending: false)
        .snapshots()
        .forEach((snapshot)  {
      snapshot.docs.forEach((element) async  {
         await fetchQuestion(element, element.data()["prize"].toString())
            .then((value)async {
           AllQuestionsOfQuiz.add(value);

          
        });
print(AllQuestionsOfQuiz);
      });
      
    });

  return AllQuestionsOfQuiz;
  }








}

通过这段代码,我在终端中得到以下输出:

I/flutter ( 8913): [{prize: 20000, question: How many workers was there to create the TAL MAHAL?, options: [60000, 70888, 75600, 789000]}]
I/flutter ( 8913): [{prize: 20000, question: How many workers was there to create the TAL MAHAL?, options: [60000, 70888, 75600, 789000]}, {prize: 10000, question: Who was awarded by the Padma Shri In The Field Of Physics ?, options: [Tulasi Gowda, Sujoy K. Guha, Harekala Hajabba, HC Verma]}]
I/flutter ( 8913): [{prize: 20000, question: How many workers was there to create the TAL MAHAL?, options: [60000, 70888, 75600, 789000]}, {prize: 10000, question: Who was awarded by the Padma Shri In The Field Of Physics ?, options: [Tulasi Gowda, Sujoy K. Guha, Harekala Hajabba, HC Verma]}, {prize: 5000, question: Who is Jethalal in TMOCK ?, options: [Husband of daya, Param Mitra Of Mehta, Son of bapuji, Father of tapu]}]

我希望在我的函数quizCreator 中返回最后一次迭代值:

[{prize: 20000, question: How many workers was there to create the TAL MAHAL?, options: [60000, 70888, 75600, 789000]}, {prize: 10000, question: Who was awarded by the Padma Shri In The Field Of Physics ?, options: [Tulasi Gowda, Sujoy K. Guha, Harekala Hajabba, HC Verma]}, {prize: 5000, question: Who is Jethalal in TMOCK ?, options: [Husband of daya, Param Mitra Of Mehta, Son of bapuji, Father of tapu]}]

请帮帮我,我在过去 2 天都被这个错误困住了。

【问题讨论】:

  • Snapshots 返回一个 Stream,其值在加载数据时流入。使用get 而不是snapshots 应该只执行一次。

标签: firebase flutter google-cloud-firestore async-await return-value


【解决方案1】:

查看文档,有两种方法可以检索存储在Cloud Firestore 中的数据。这些方法中的任何一种都可以用于文档、文档集合或查询结果。

当您使用get() 时,您只能“获取单个文档的内容”一次。这是一种“一劳永逸”的情况:如果(后端)Firestore 数据库中的文档发生更改,您将不得不再次执行get() 才能看到它。

另一方面,如果您使用onSnapshot() 方法,您将一直在收听文档,如doc 中所述

您可以使用Promise 包围forEach 循环,如果您希望在forEach() 循环中更新多个文档,还需要使用Promise.all

您也可以使用以下语法返回 Promise.all():

.... return Promise.all(promises); }) });

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2022-09-23
    • 2020-11-10
    • 2020-08-31
    • 2019-10-01
    • 2021-05-30
    相关资源
    最近更新 更多