0

I am Using Firestore with flutter and trying to fetch data from sub-collection.

I am using async and await to fetch the data so the data fetching is taking around 8-10 seconds.

Here is the example of Structure of my firestore

Company->company_id->Year->2023 ->06->(list of dates)->Reimbursement->reimbursement_id

enter image description here

Company is the Collection and company_id is the document and Year is the Sub-collection and so on.

I am trying to fetch the data of current Month so I am going inside 08 collection and want to check in all the dates available that the Reimbursement Collection exits or not. If Reimbursement Exist i want to store that data in the list.

Here is the code that i used.

getAllReimbursement(month,year) async {
    allReimbursement.clear();
    
    List<ReimbursementModel> reimbursementList=[];
    var monthRef=await FirebaseFirestore.instance.collection("Company").
    doc(ConstantValue.companyId).collection("Year").doc(year).collection(month).get();
    var dateDocs=monthRef.docs;

      for(var j=0;j<dateDocs.length;j++) {
        var reRef=await dateDocs[j].reference.collection("Reimbursement").where(
            "sendTo", isEqualTo: ConstantValue.userEmail).get();
          reRef.docs.forEach((element) {
            reimbursementList.add(ReimbursementModel.fromJson(element.data()));
          });

      }
      allReimbursement=reimbursementList;
      return reimbursementList;
  }

This is my code to fetch the data. This code is taking around 8-10 seconds to fetch as it is going through loop of all days in a month. Is there any better optimized way to do this same Task?.

enter image description here

I am using Syncfusion dataGrid to create table.For that I need the list of data to be fetched before loading the page

1 Answers1

0

You're now loading the reimbursements for each month in turn, only starting with the next month when the previous month has been loaded.

One option to make the loading faster is to load the reimbursements for all months in parallel, by not using await inside the for loop - but using a single Future.wait call for all queries. For more on this, see Dartlang wait more than one future

Alternatively, since it seems that all Reimbursement collections you are loading from seem to be under a single parent document, you can consider using the "load all collections from a path" trick that @samthecodingman showed in his answer here: CollectionGroupQuery but limit search to subcollections under a particular document

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807