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

Flutter set Value to zero when it WOULD fall below zero

I am trying to create a drink tracker where I can track my hydration during the day
Picture

Therefore I created this app. The problem is: When I press "add" 500ml, then press "remove" 750ml it goes to minus 250ml. I can only manage to set the counter to zero when I press any decrement button again after it is already a negativ value! Here is the code:

      Future<void> _decrementCounter({required int amount}) async {
    final prefs = await SharedPreferences.getInstance();

    setState(() {
      if(_counter<=0||_counter==-250){
        _counter = prefs.getInt('counter') ?? 0;
        _counter = 0;
        prefs.setInt('counter', _counter);
      }else{
      _counter = (prefs.getInt('counter') ?? 0) - amount;
      prefs.setInt('counter', _counter);
      }
    });
  }

I hope you understand my usecase and can help me with this issue!

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

>Solution :

I would just check if the current counter minus the passed value is less than 0. If it is, then I would put 0 in counter and otherwise the calculation. And then you save that in your SharedPreferences again.

setState(() {
    _counter = (_counter - amount) < 0 ? 0 : (_counter - amount);
    prefs.setInt('counter', _counter);
  }
}
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