I wanna make a counter like the one every food app has. I already had the increment and decrement function, and it works perfectly. But I wanna make that user can also put a specific number by typing it, and increment & decrement function works on that too.
how can I do that?
here is the counter function
int _counter = 0;
_incrementCounter() {
setState(() {
if (isChecked = true && _counter < (widget.productDetail['stock'])) {
_counter ;
}
});
}
_decrementCounter() {
setState(() {
if (_counter > 0) {
_counter--;
}
});
}
and here is the counter
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Minus
Expanded(
flex: 1,
child: InkWell(
onTap: () {
_decrementCounter();
},
child: Container(
alignment: Alignment.center,
// padding: EdgeInsets.only(
// right: 10),
child: Icon(
Icons.remove,
color: Color(0xffFFFFFF),
),
),
),
),
// Qty Number
Expanded(
flex: 1,
child: Text(
'$_counter',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
),
// Add
Expanded(
flex: 1,
child: InkWell(
onTap: () {
_incrementCounter();
},
child: Container(
alignment: Alignment.center,
child: Icon(
Icons.add,
color: Color(0xffFFFFFF),
),
),
),
),
],
),
), // Counter
CodePudding user response:
To take input, you need to replace Text
with TextFiled
and use TextEditingController
to handle the update
The code inside state
final TextEditingController controller =
TextEditingController.fromValue(TextEditingValue(text: "0"));
int _parseCounter() {
return int.tryParse(controller.text) ?? 0;
}
_incrementCounter() {
setState(() {
controller.text = (_parseCounter() 1).toString();
});
}
_decrementCounter() {
setState(() {
if (_parseCounter() > 0) {
controller.text = (_parseCounter() - 1).toString();
}
});
}
And replace Text
widget with TextField
using controller.
TextField(
controller: controller,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),