How do I set a interval in TextField
? I want it accepting only numbers in the range 1-100
...
Here is my widget:
TextField(
inputFormatters: [
LengthLimitingTextInputFormatter(3)
],
cursorColor: Colors.white,
keyboardType: TextInputType.number,
textInputAction: TextInputAction.search,
textAlign: TextAlign.right,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
decoration: InputDecoration.collapsed(
hintText: '',
hintStyle: TextStyle(fontSize: 14),
),
),
Solution 1: solarc
You can create your own input formatter that can limit the range of numbers like this:
class LimitRangeTextInputFormatter extends TextInputFormatter {
LimitRangeTextInputFormatter(this.min, this.max) : assert(min < max);
final int min;
final int max;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
var value = int.parse(newValue.text);
if (value < min) {
return TextEditingValue(text: min.toString());
} else if (value > max) {
return TextEditingValue(text: max.toString());
}
return newValue;
}
}
Then add it to your inputFormatters:
inputFormatters: [
LengthLimitingTextInputFormatter(3),
LimitRangeTextInputFormatter(1, 100),
],
With this if the user types a number greater than 100 the text field will change it back to 100.