Flutter Firestore Get All the Documents from Collections and Sub-collections

Created At: 2022-09-25 20:25:53 Updated At: 2023-02-13 08:17:20

We will see how to get all the data or documents from firebase firestore database. We will also see how to get sub documents

The most important part of this below query

  final QuerySnapshot<Map<String, dynamic>> questionsQuery =
          await quizePaperFR.doc(quizPaper.id).collection('questions').get();

The above line gets a sub collection based on collection and document ID.

Here you can replace quizePaperFR with 

FirebaseFirestore.instance.collection("products")

The above line gets a collection name "products". You can replace this with your collection name.

You need to pass a document ID inside .doc() function. 

Then it will get a sub collection's documents based on collection and document ID.

So the core query for getting all the sub collections documents is below

  final QuerySnapshot<Map<String, dynamic>> questionsQuery =
          await FirebaseFirestore.instance.collection("collection name").doc(document.id).collection('sub-collection name').get();

So the above code will return a Map of documents from sub-collection.

We take those documents and turn them into a list using toList()

questions = questionsQuery.docs
          .map((question) => Question.fromSnapshot(question))
          .toList();

So questions become a list.

Then we did the below operation

collection-->document.id-->sub-collection-->sub-document.id-->sub-sub-collection->sub-sub-documents

Now we do the below operations

QuerySnapshot<Map<String, dynamic>> answersQuery =
            await quizePaperFR
                .doc(quizPaper.id)
                .collection('questions')
                .doc(_question.id)
                .collection('answers')
                .get();

The complete code

  void loadData(QuizPaperModel quizPaper) async {
    quizPaperModel = quizPaper;
    loadingStatus.value = LoadingStatus.loading;
    try {
      final QuerySnapshot<Map<String, dynamic>> questionsQuery =
          await quizePaperFR.doc(quizPaper.id).collection('questions').get();
      final questions = questionsQuery.docs
          .map((question) => Question.fromSnapshot(question))
          .toList();
      print("...questions....${questions[0].answers}");
      quizPaper.questions = questions;
      for (Question _question in quizPaper.questions!) {
        final QuerySnapshot<Map<String, dynamic>> answersQuery =
            await quizePaperFR
                .doc(quizPaper.id)
                .collection('questions')
                .doc(_question.id)
                .collection('answers')
                .get();
        final answers = answersQuery.docs
            .map((answer) => Answer.fromSnapshot(answer))
            .toList();
        _question.answers = answers;
      }
    } catch (e) {}

    if (quizPaper.questions != null && quizPaper.questions!.isNotEmpty) {
      allQuestions.assignAll(quizPaper.questions!);
      currentQuestion.value = quizPaper.questions![0];
      _startTimer(quizPaper.timeSeconds);
      loadingStatus.value = LoadingStatus.completed;
    } else {
      loadingStatus.value = LoadingStatus.noReult;
    }
  }

Get Document ID

Let's how to get document id from firestore after creating document. After adding document you should use then() function. 

then() function takes DocumentReference object.  And it returns a of DocumentReference type.

     await FirebaseFirestore.instance.collection("chat").add({
       "field1":"this is a text",
       "field2":10
     }).then((DocumentReference doc){
       print("my document id is ${doc.id}");
     });

See after add() function we used then() function to get document id.

Comment

Add Reviews