I’m trying to get a percentage of a number. In some cases the numerator of the division operation could be zero.
I brought out a logical operation for this in flutter and it seems to be messing with my brain. It sometimes returns Unsupported operation: Infinity or NaN toInt
. The problem is it gives me the expected result after hot reload, then when I reload again then the problem Unsupported operation
comes again.
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%)"),
],
);
}eles {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%)"),
],
);
} eles {return...}
What might posible be the problem?
2
Answers
Instead of
I did it this way and i got a good result
In this case, whether the numerator or dinomenator is zero, the percentage is always zero since zero devided by any number is zero
Remove the below code;
Why? it’s a redundant code.
You’re checking if
totalDriver
is zero before performing the division operation. This ensures that the denominator of the division operation is never zero, which would result inInfinity
orNaN
. Therefore, theisNaN
andisInfinite
checks are not necessary because you’re already handling the case where the denominator could be zero.This is a modified code;
Here, if
totalDriver
is zero, the code will return a row with a text widget displaying "0%". IftotalDriver
is not zero, the code will perform the division operation and calculate the percentage.