How to input only numbers in TextField in Flutter
For fields where only numerical input makes sense (such as age, quantity, or price), limiting input to numbers can enhance the user experience. It reduces the likelihood of users making mistakes or entering invalid data.
Toady we will learn how to input only numbers in TextField in Flutter
Input Only Numbers In TextField Flutter
This can be achieved by two properties of textField. First one is keyboardType and second is inputFormatter. Let’s see how to set values of these properties.
TextFormField(
controller: _controller,
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly],
decoration: InputDecoration(
labelText: "whatever you want",
hintText: "whatever you want",
icon: Icon(Icons.phone_iphone)
)
)
keyboardType:
TextInputType.number: This sets the keyboard type for the input field to a numeric keyboard. This means that when the user taps on the text field to input data, the keyboard that appears will be a numeric keyboard, making it easier for the user to input numbers.
InputFormatters:
[FilteringTextInputFormatter.digitsOnly],: This line specifies an input formatter that allows only digits (0-9) to be entered. FilteringTextInputFormatter.digitsOnly restricts the input to only numeric values, preventing the user from entering non-numeric characters.