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

if has bad state return something else Flutter

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

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

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

but I still get the bad state: no element error

what can I do to fix it?

>Solution :

The problem here is that reduce wants at least one element. If you don’t have any elements it will therefore fails. 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.

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