Input formatting — Flutter

TheBoringDeveloper
Jul 5, 2020 · 4 min read

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

Use inputFormatters field of TextField

Optional input validation and formatting overrides.

Formatters are run in the provided order when text input changes.

Flutter has 3 built-in formatters

  1. BlacklistingTextInputFormatter — In simple words, used to prevent insertion of characters using patterns
  2. WhitelistingTextInputFormatter — In simple words, used to allow insertion of certain characters using patterns
  3. 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-

  1. Example 1- Create a text field which does not allow spaces
  2. Example 2- Create a text field which allows only letters and spaces like a Name field
  3. Example 3- Create a text field to enter code
  4. 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

More flutter blogs-

https://www.twitter.com/FlutterComm

Flutter Community

Articles and Stories from the Flutter Community