flutter 中的求和问题不起作用,如何在导航栏中显示总收入?

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

我想对集合名称(“januaryi”)下的所有文档的字段(一月份的总收入)求和。我尝试了一个不起作用的函数。有没有什么方法可以在底部导航栏中调用函数并显示求和。

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

底部导航栏:

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

显示总收入错误:

像您尝试的那样在构建函数内部更改值不是好的做法。 您可以像这样在 totalmoney() 函数中简单地设置一个 totalIncome 变量:

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;
  });
}

然后在您的 initState() 方法中调用此方法。 用新变量 $totalIncome 替换 ${totalmoney()}。不要忘记在您的状态 Class.

顶部初始化它

此外,请尝试在 Whosebug 中格式化您的代码,而不是发布图片。