Search code examples
firebasefluttervisual-studio-codeflutter-bottomnavigation

Summation problem in flutter is not working, How can I show the total income in navigation bar?


I want to sum the field (total income in January) of all document under the collection name ("januaryi").I tried a function that is not working. Is there any way to call function and show summation in bottom navigation bar.

Flutter Firebase:

Valid XHTML

Function:

class _JanuaryState extends State<January>{
  totalmoney() async {
   int total = 0;
   var snapshot = 
       await Firestore.instance.collection("Januaryi").getDocuments();
   if (snapshot == null){
     return 0; 
   }
   snapshot.documents.foreach((doc) {
     total = total + int.parse(doc.data['income']);
   });
   return total;
 }
}

Bottom Navigation Bar:

  bottomNavigationBar: Container(
     child: ListTile(
     title: Text('Total'),
     subtitle: Text("${totalmoney()}"),
    )),
  );      

Showing error in total income:

Valid XHTML


Solution

  • It is not good practice to change values inside of the build function like you try to do. You can simply set a totalIncome variable inside your totalmoney() function like this:

    totalmoney() async{
      int total = 0;
      var snapshot = await Firestore.instance.collection("Januaryi").getDocuments();
      setState((){
        if(snapshot == null)
          totalIncome = 0
        snapshot.documents.forEach((doc){
          total+=int.parse(doc.data['income']);
        });
        totalIncome = total;
      });
    }
    

    Then call this method inside your initState() method. Replace the ${totalmoney()} by the new variable $totalIncome. Dont forget to initialize it at the top of your State Class.

    Also, try to format your code inside StackOverflow instead of posting images.