4

I'm building a Self-learning app with differente questions types. Right now, one of the questions have a field containing a list of DocumentReferences:

enter image description here

In Flutter, I have the following code:

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

Now, with "questionTemp" I can access all the fields (lesson_id,options,question_type, etc..), but when it comes to the "cards" field, how Can I access the data from that document reference?

Is there a way to tell firestore.instance to get the data from those references automatically? Or do I need to make a new call for each one? and, if so, how can I do that?

Thank you for your support in advance!

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Jeoxs
  • 163
  • 1
  • 2
  • 10

1 Answers1

4

Is there a way to tell firestore.instance to get the data from those references automatically? Or do I need to make a new call for each one?

No there isn't any way to get these documents automatically. You need to build, for each array element, the corresponding DocumentReference and fetch the document.

To build the reference, use the doc() method

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

and then use the get() method on this DocumentReference.

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

Concretely, you can loop over the cards Array and pass all the Futures returned by the get() method to the wait() method which "waits for multiple futures to complete and collects their results". See this SO answer for more details and also note that "the value of the returned future will be a list of all the values that were produced in the order that the futures are provided by iterating futures."

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • Thank you very much! I handled the problem with this recommendation using the Future.wait(). – Jeoxs Oct 28 '21 at 19:38