Input formatting — Flutter
Welcome! Today we will learn about adding input formatting in Flutter
To be up-to-date check out my instagram page.
Lets start
We will be doing input formatting in TextField in Flutter
How?
Use inputFormatters field of TextField
What does it do?
Optional input validation and formatting overrides.
Formatters are run in the provided order when text input changes.
Built-in formatters
Flutter has 3 built-in formatters
- BlacklistingTextInputFormatter — In simple words, used to prevent insertion of characters using patterns
- WhitelistingTextInputFormatter — In simple words, used to allow insertion of certain characters using patterns
- LengthLimitingTextInputFormatter — Allows insertion of only certain number of characters
NOTE: Using BlacklistingTextInputFormatter and WhitelistingTextInputFormatter requires basic knowledge of regex.
We will learn using examples
We will use 4 examples to understand input formatting-
- Example 1- Create a text field which does not allow spaces
- Example 2- Create a text field which allows only letters and spaces like a Name field
- Example 3- Create a text field to enter code
- Example 4- Create a text field to enter amount
Example 1
Create a text field which does not allow spaces
Output:
What did we do?
- We did not allow any whitespace character using \s
Example 2
Create a text field which allows only letters and spaces like a name field
Output:
What did we do?
- We allow more than 1 letter and whitespace characters, all other characters are considered invalid
Example 3
Create a text field to enter code
Here are the requirements-
- Must be 6 characters
- Should consist of only numbers and letters
- Uppercase letters only
Output:
What did we do?
Remember, when I told you that input formatters are called in order?
- We are first converting the input from lower case to upper case
- Then we are allowing only letters and uppercase letters
You could force user to input only upper-case letters, but that wouldn’t be good UX
Example 4
Create a text field to enter amount
Requirements:
Allow numbers with only two decimal digits
Here are some stack overflow solutions-
Here is my solution-
Lets check the output:
BUT!! We have a bug too
Looks like we cannot type numbers in format (.**) with starting as decimal
What did we do?
We changed \d+ to \d? and made the numbers before decimal optional
Lets check the output now-
Thank you for staying till the end