I am trying to create a drink tracker where I can track my hydration during the day
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!
CodePudding user response:
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);
}
}