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:



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(['income']);
   return total;

Bottom Navigation Bar:

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

Showing error in total income:



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();
    if(snapshot == null)
      totalIncome = 0
    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.

Answered By – Max Mustermann

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *