'Flutter TextField only positive numbers
Is there a way in flutter to make a TextField only accept numbers greater than zero? I currently only allow numbers via the following code:
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly],
Now I want to prevent the TextField to have the value zero while still generally allowing to type zeros. Thus, allowing to enter 100 and preventing to enter 001.
I don't want to achieve this by listening to input changes and then manually erasing zeros, or by similar methods. I am looking for a built-in solution.
Solution 1:[1]
digitsOnly calls FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
so just replace it with FilteringTextInputFormatter.allow(RegExp(r'^[1-9][0-9]*'))
Solution 2:[2]
add this code to TextFormField
inputFormatters:[FilteringTextInputFormatter.allow(RegExp("[0-9]"))],
it works for me.
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 | |
| Solution 2 |
