I have this BMI Calculator and I want that the Height can not be under 100 (cm). For that I created a TextFormField
which looks like the following:
TextFormField(
onFieldSubmitted: (value) {
setState((){
_heighController.text= value;
if (int.parse(value) >= 100) {
value = "100";
}
value=_heighController.text;
});
},
inputFormatters: [
LengthLimitingTextInputFormatter(3),
FilteringTextInputFormatter.allow(RegExp(r'^[1-9][0-9]*')),
],
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
style: const TextStyle(fontSize: 16, color: Colors.white),
controller: _heighController,
cursorColor: Colors.white,
decoration: InputDecoration(hintText: "in cm", hintStyle: TextStyle(color: Colors.white)),
),
as you can see, I already tried to add onFieldSubmitted
, but this doesn't work out like I planned. When I write 90 e.g., it accepts 90 when I press the "enter" button on my keyboard. But when I update the state for this widget with my Plus or minus button (see picture below) it goes to 100 automatically. I want that it goes to 100 every time I leave the "editing option" from this field and the input is below 100. How do I realize that?
CodePudding user response:
You should change the value of the _heighController on your "onFieldSubmitted" function, like this:
onFieldSubmitted: (value) {
setState((){
if (int.parse(value) <= 100) {
value = "100";
}
_heighController.text= value;
});
},
Your error was to attribute the value to your controller before checking the validity. And after, you set the value of your controller to the parameter of the function, which is pointless in this case.