Home > database >  Flutter TextField only positive numbers
Flutter TextField only positive numbers

Time:04-12

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.

CodePudding user response:

digitsOnly calls FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))

so just replace it with FilteringTextInputFormatter.allow(RegExp(r'^[1-9][0-9]*'))

CodePudding user response:

add this code to TextFormField

inputFormatters:[FilteringTextInputFormatter.allow(RegExp("[0-9]"))],

it works for me.

  • Related