Flutter Firestore数值相加报错:kcal变量与progress字段求和失败
问题解决:Firestore字段与本地变量相加报错
问题根源
你犯了一个类型错误:nutr是Firestore返回的整个文档数据Map对象,并非你需要的progress字段数值,直接拿它和kcal2相加必然报错。你已经提前获取了this.progress = nutr['progress'];,但相加时却误用了整个Map对象而非正确的数值变量。
修正后的代码
Future addMeal() async { Map<String, dynamic>? nutr; await FirebaseFirestore.instance .collection('usersData') .doc(FirebaseAuth.instance.currentUser!.uid) .get() .then((doc) => nutr = doc.data()); print('test'); if (nutr != null) { // 取出progress字段的数值,明确类型为num(兼容int/double) final currentProgress = nutr['progress'] as num; setState(() { // 使用正确的数值变量与kcal2求和 progressAdd = currentProgress + kcal2; }); // 数据库更新操作移出setState,避免UI更新逻辑与业务逻辑耦合 await FirebaseFirestore.instance .collection('usersData') .doc(FirebaseAuth.instance.currentUser!.uid) .update({'progress': progressAdd}); } else { print('test2'); return showDialog( context: context, builder: (context) { return AlertDialog( backgroundColor: mainFontColor().tsubColor, title: Text( ':/', textAlign: TextAlign.center, style: GoogleFonts.lato( fontWeight: FontWeight.w600, color: Colors.white), ), content: Container( height: 120, width: 250, child: Column(children: [ Text( 'Something went wrong!', style: GoogleFonts.dosis(color: Colors.white), ), SizedBox( height: 5, ), Text( 'Go back and try again!', style: GoogleFonts.dosis(color: Colors.white), ), SizedBox( height: 20, ), Container( height: 40, width: 180, child: ElevatedButton( child: Text('OK'), style: ElevatedButton.styleFrom( backgroundColor: mainFontColor().tsubColor2), onPressed: () => Navigator.pop(context)), ) ]), ), ); }); } }
额外优化提示
- 给
nutr指定明确类型Map<String, dynamic>?,避免动态类型带来的潜在风险。 - 确保
kcal2是数值类型(int/double),如果是字符串需先转换,例如double.parse(kcal2)。 - 将Firestore更新操作从
setState中移出,setState仅负责UI状态更新,业务逻辑单独处理更清晰。
内容的提问来源于stack exchange,提问作者Maniak
相关产品推荐
相关产品推荐

