'how to not return negative values when hit decrement value at 0
I am trying to implement value which doesn't allow user to pass negative value as this button functioning to print pages.
class _QuantityCounterState extends State<QuantityCounter> {
int _counter = 0;
void increment() {
setState(() {
_counter++;
});
}
void decrement() {
setState(() {
_counter--;
});
}
Solution 1:[1]
void decrement() {
setState(() {
_counter=<0 ? _counter=0 : _counter--;
});
}
Solution 2:[2]
More elegant solution:
import 'dart:math';
void decrement() {
setState(() {
_counter = max(_counter-1, 0);
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anggadaz |
| Solution 2 | Kerim |
