简体   繁体   中英

Unable to return list from Firebase Firestore In Flutter

I am currently working on a Quiz App In Flutter. I am fetching data from firebase and successfully created the list of maps that contained my required data.

But the problem is I am doing a forEach loop on snapshot.docs and adding the values in an empty AllQuestionsOfQuiz List but I am unable to return it from the functions.

I don't know what I am missing here is the code:

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








}

By this code I am getting this following output in terminal:

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]}]

I want the this last iteration value to be returned in my function 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]}]

Please help me I am stuck at this bug for last 2 days.

Reviewing documentation, there are two ways to retrieve data stored in Cloud Firestore . Either of these methods can be used with documents, collections of documents, or the results of queries.

You only "obtain the content of a single document" once when you use get() . It is a "get and forget" situation: If the document in the (back-end) Firestore database changes, you will have to execute get() again to see it.

On the other hand, if you use the onSnapshot() method, you will be listening to a document all the time, as mentioned in the doc

You can use a Promise to surround the forEach loop, also you need to use Promise.all if you wish to update multiple docs within the forEach() loop.

You can alternatively use the following syntax to return Promise.all():

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM