-1

I have this code that should calculate total sum of a list:

int _counter = 0;

Future getTotal(item) async {
int counter = 0;

_totalPrice.add(int.parse(item));
_totalPrice.forEach((element) => counter += element);

print('LIST: $_totalPrice');
print('SUM: $counter');
return counter;

}

The _counter should be global variable, so I can use it in other functions, but I am getting this strange issue that almost squares after second click of function, here is the result after I click it twice, instead of adding 1 item, the SUM is larger:

enter image description here

As you can see, the result of the SUM should be 312, not 468, for some reason it calculates it wrongly. I just need it to calculate correctly the sum of the list each time the function is invoked.

arbiter
  • 421
  • 7
  • 29
  • See this answer https://stackoverflow.com/a/19621386/10285344 – ASAD HAMEED Jan 06 '21 at 14:49
  • I agree: Using a more functional style will help you avoid 'inexplicable' errors. However, your linked answer is not correct, as it fails on empty lists. Use `fold()` instead. – rgisi Jan 06 '21 at 15:58
  • So something like this? `sum = given_list.fold(0, (previous, current) => previous + current);` – arbiter Jan 06 '21 at 16:50

1 Answers1

1

first you must convert int types to string then parse it to int, this is must safe way to parsing erverthing that can be parse to int. other problem is that you define _counter and you must reset it in function, you wrongly just define it again!

getTotal(item){
_counter = 0;
_totalPrice.add(int.parse(item.toString()));
_totalPrice.forEach((element) => _counter += element);

print('LIST: $_totalPrice');
print('SUM: $_counter');
return _counter;

}

  • 1
    This is okay answer, but not what I'm looking for exactly. The thing is recalling the _counter doesn't really work since I need the global one. – arbiter Jan 06 '21 at 17:59
  • you must setState in this function at the end before return and it will work, but the best way is using global state manajment like GetX – Nastaran Mohammadi Jan 07 '21 at 17:31