Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of TextEditingControllers

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading