Search code examples
flutterstream-builder

How to initialise Firestore query in initState in flutter


I am trying to load the data from Firestore, with the help of streambuilder i am getting the respective data and displaying it to the user.

I am passing the value to a variable called 'total' and this total is inialised with 0 and when i try to show this total value it first should the default(0) value and the it takes the value from Firestore.

Below you can see the code

            StreamBuilder<DocumentSnapshot>(
                stream: FirebaseFirestore.instance.collection('UserData').doc(getUid()).snapshots(),
                builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
                  if (!snapshot.hasData) return const Text("Loading...");
                  final DocumentSnapshot? document = snapshot.data;
                  final Map<String, dynamic> documentData = document?.data() as Map<String, dynamic>;

                  accountList = (documentData['accounts'] as List).map((accountList) => accountList as Map<String, dynamic>).toList();
                  // getTotalFund(accountList);
                  List amountData=[];
                  double convertAmount;

                  for(int i=0; i<accountList.length;i++){
                    if(accountList[i]['accountType'] == 'Savings' || accountList[i]['accountType'] == 'Cash' ){
                      amountData.add(double.parse(accountList[i]['amountBalance'].replaceAll(',','')));
                    }
                  }
                  convertAmount = amountData.reduce((value, element) => value + element);
                  totalFund = amountFormat.format(convertAmount);

                  return Text(
                    documentData['name'],
                    style: const TextStyle(
                      fontSize: 16,
                      fontFamily: "Gilroy SemiBold",
                    ),
                  );
                }),

the value total amount i am getting in the Text widget.

Text('\u{20B9} ', style: TextStyle(color: Color(0xff9c9c9c), fontFamily: "Gilroy Medium", fontSize: 23)),
Text(totalFund.toString(),style: const TextStyle(color: Colors.black, fontFamily: "Gilroy Bold", fontSize: 35)),

how to load the totalFund in initState so it will not show the null value.

screenshot


Solution

  • try this:

     Future<DocumentSnapshot> getDoc() async {
        return await FirebaseFirestore.instance.collection('UserData').doc(getUid());
     }
    

    then set FutureBuilder as parent of your body widget like this:

    FutureBuilder(future: getDoc(),
           builder: (context, snapshot){
                if (snapshot.connectionState == ConnectionState.waiting) {
                      return const Text("Loading...");
                    } else {
                      if (snapshot.hasError) {
                        return const Text("error");
                      } else {
                        final DocumentSnapshot? document = snapshot.data;
                        final Map<String, dynamic> documentData =
                            document?.data() as Map<String, dynamic>;
    
                        accountList = (documentData['accounts'] as List)
                            .map((accountList) => accountList as Map<String, dynamic>)
                            .toList();
                        // getTotalFund(accountList);
                        List amountData = [];
                        double convertAmount;
    
                        for (int i = 0; i < accountList.length; i++) {
                          if (accountList[i]['accountType'] == 'Savings' ||
                              accountList[i]['accountType'] == 'Cash') {
                            amountData.add(double.parse(
                                accountList[i]['amountBalance'].replaceAll(',', '')));
                          }
                        }
                        convertAmount =
                            amountData.reduce((value, element) => value + element);
                        totalFund = amountFormat.format(convertAmount);
    
                        return yourBodyWidget;
                      }
              })