Home > OS >  if has bad state return something else Flutter
if has bad state return something else Flutter

Time:07-27

So I have a method in my controller that calculates me how many values I have in total

  get gesamtAnzahl => _products.entries
  .map((product) => product.value)
  .toList()
  .reduce((value, element) => value   element)
  .toStringAsFixed(2);

the problem is that I get each product pretty late So it has a bad state when I try to calculate these values at a time where no product exists

I tried doing something like this

"${controller.gesamtAnzahl == null ? "0" : controller.gesamtAnzahl}"

but I still get the bad state: no element error

what can I do to fix it?

CodePudding user response:

The problem here is that reduce wants at least one element. If you don't have any elements it will therefore fail. You could instead use fold which have a starting value that can be returned in case no elements are found.

There are also some other questionable code in your example but something like this should work:

  get gesamtAnzahl => _products.values
  .fold<int>(0, (value, element) => value   element)
  .toStringAsFixed(2);

Should be noted that this would only work if you actually wants "0.00" to be returned in case _products are empty.

  • Related