I was trying to get the sum of multiple TextEditingController via this function .
void _CalculTotal() {
double total = 0;
for (var j = 0; j < widget.controllers.length; j++) {
//print(widget.controllers[i].text);
total = double.parse(widget.controllers[j].text);
print(total);
}
}
I’m getting this error :
Invalid double
>Solution :
Try replacing
total = double.parse(widget.controllers[j].text);
with
total += double.tryParse(widget.controllers[j].text) ?? 0;
Problem 1: Instead of adding values to total you are setting them.
Problem 2: You have to make sure that the entered text can be parsed to double value. So, using tryParse will parse it to double if possible or just add 0 for that entry.
And also you are printing the total in every iteration. Better to do it after the loop. So your final code will look something like this:
void _CalculTotal() {
double total = 0;
for (var j = 0; j < widget.controllers.length; j++) {
//print(widget.controllers[i].text);
total += double.tryParse(widget.controllers[j].text) ?? 0;
}
print(total);
}