Change Keyboard Type Dynamically in Textfield

How to change keyboard type from Text to Number while typing in TextField after 4th character.

1 Like

Keep a variable that holds the type of keyboard called keyboardType… initial value will be text…

Textfield has a callback called onChanged…

Keep track of the character length in that callback…

Once the length is greater than 4 and only if keyboardType is text and then, call setState and change the keyboard type variable to number in the same setState function.
setState calls the build method and it will render a number type keyboard.
Also, have variable to retain the 4 characters entered and assign this variable to initialValue parameter of textfield…
On onChanged assign the value to this variable, so that the first 4 characters are not lost…

1 Like

Thanks for the solution. I have tried this but did not worked, can you please share code snippet for the same.

From experience I thought setState should do the trick.
I tried the solution that I suggested and it didn’t work. Sorry!

The parameter “keyboardType” is of type TextInputType, when I checked the definition of TextInputType class, I found out the constructor of this class is const.
That means once it is defined it cannot be changed. Hence the suggested solution doesn’t work.
Calling setState does trigger the build method, since the constructor of TextInputType is const, the keyboradType will not change.

I found a way to achieve this, but not really happy about it as it is sort of a hack.
After 4th character, default text keyboard is minimized, after that when the user taps on the text field number keyboard pops up.


Thanks for the solution.I will check this.

1 Like