Flutter计算百分比报错Unsupported operation: Infinity or NaN toInt
问题描述
我需要计算一个数值的百分比,部分场景下除法运算的分子可能为0。在Flutter中实现相关逻辑后,偶尔会抛出错误:Unsupported operation: Infinity or NaN toInt,热重载后有时能得到预期结果,但再次重载时问题会重复出现。我先尝试判断percentage是否为NaN或无穷大,之后又添加了判断totalDriver是否为0的逻辑,但问题依然存在,请问这是什么原因?
相关代码
int? totalDriver = 0; final totalCompleted = snapshot.data;//I got this from streamBuilder and everything is perfect here. final percentage = ((totalCompleted! / totalDriver!) * 100).floor();//The starts from here. So I brought this logic. if (percentage.isNaN || percentage.isInfinite) { return Row( children: [ SizedBox( width: screenWidth * 0.4, child: Text( "$completedString:", style: const TextStyle(color: Colors.green), ), ), Text("$totalCompleted (0%)"), ], ); }else {return...} //I also later added this logic (So in case the denominator id 0, the percentage will be infinity, so if it's infinity it should return (0%))but it still persists. if (totalDriver == 0) { return Row( children: [ SizedBox( width: screenWidth * 0.4, child: Text( "$completedString:", style: const TextStyle(color: Colors.green), ), ), Text("$totalCompleted (0%)"), ], ); } else {return...}
问题原因
核心问题是你的判断逻辑写在了百分比计算之后:
- 当
totalDriver为0时,执行totalCompleted! / totalDriver!会得到Infinity,紧接着调用.floor()方法时,会直接触发Unsupported operation: Infinity or NaN toInt异常——此时你的判断代码还没来得及执行,程序就已经报错了。 - 另外,你写的两个判断是顺序执行的,第一个判断如果触发return,第二个判断根本不会运行;但最关键的还是计算步骤先于判断,导致异常提前抛出。
解决方案
把判断逻辑提前到百分比计算之前,先处理分母为0的情况,再执行计算:
int? totalDriver = 0; final totalCompleted = snapshot.data; // 先处理分母为0或数据为空的边界情况 if (totalDriver == 0 || totalCompleted == null) { return Row( children: [ SizedBox( width: screenWidth * 0.4, child: Text( "$completedString:", style: const TextStyle(color: Colors.green), ), ), Text("${totalCompleted ?? 0} (0%)"), ], ); } // 分母合法时再计算百分比 final percentage = ((totalCompleted / totalDriver) * 100).floor(); // 额外做一层安全判断,防止其他异常情况 if (percentage.isNaN || percentage.isInfinite) { return Row( children: [ SizedBox( width: screenWidth * 0.4, child: Text( "$completedString:", style: const TextStyle(color: Colors.green), ), ), Text("$totalCompleted (0%)"), ], ); } // 正常情况返回对应UI return ...;
额外提示:代码中你用!强制解包totalCompleted,如果snapshot.data可能为null,会引发空指针异常,建议一起加入null判断(如上代码所示)。
内容的提问来源于stack exchange,提问作者EBENEZER OCANSEY
相关产品推荐
相关产品推荐

