How to use Flutter Textformfield Widget

Flutter textformfield widget in Flutter app is used to take input from the user and process it. We’ll go through the parameters of textformfield with easy code examples fully so you can customize it in your project with ease.

What is Flutter Textformfield and its importance in a Flutter App?

As I have explained in the beginning that this widget is used to take data from the user. For instance, in a login screen, the user can enter his/her email and password and for other screens he/she can put the required data using a field that can a Flutter textfield, textformfield or some other field that can take inputs. So, that’s the purpose and importance of textformfield widget.

Let’s now leave the boring part and jump into the practical code examples.

Syntax

TextFormField()

flutter textformfield widget

flutter textformfield focused

This is the simple syntax of textformfield and this is how we can call this widget. In the above image we see a textformfield with a default underline border. We also gave it some input to prove that its a field that accepts input from a user.

Flutter Textformfield Decoration Parameter (for designing the field)

decoration: InputDecoration()

This parameter is used to design the field. It takes an InputDecoration class and by using its properties, we can customize our field however we like. I’ll explain it in the below section with proper code examples.

Parameters of Textformfield Flutter

These are:

  1. decoration (this will cover the input decoration in detail with multiple code examples)
  2. autofocus
  3. focusNode
  4. canRequestFocus
  5. validator
  6. style

Practical Code Examples with Explanations

Example 1: Flutter Textformfield Decoration

In this block, we’ll cover the decoration paramater of textformfield.

Example 1.1: hintText parameter

decoration: InputDecoration(
              hintText: 'Enter your name'
             )
flutter textformfield hintText parameter
This is how you can pass the InputDecoration class to the decoration parameter.
We used the Flutter textformfield hintText parameter which takes a string value. This is the text that will show on the field when its empty or the user haven’t entered anything yet. Its purpose is to guide the user about what type of data the user has to submit.

Example 1.2: hintStyle parameter

hintStyle: TextStyle(
      color: Colors.green.withOpacity(.4),
      fontSize: 18,
      fontWeight: FontWeight.w500,
                  )
flutter textformfield hintstyle
The hintStyle is used to give style to the hint. It takes a text style widget. To demonstrate it, we gave it a color, size of text and make it a bit bold. You can play with other properties of text style to decorate your hint text more.

Example 1.3: labelText and labelStyle

labelText: 'This is label text',

labelStyle: TextStyle(
      color: Colors.purple,
                  )
flutter textformfield labeltext
textformfield label style
This labelText parameter also works like hint text. Its shown where the input will be given by user when the textformfield is not yet focused.
If you have hint text specified then still label text will be shown when unfocused. When you focus the field then by default the label text will move to the top left position. When the field is empty and focused, then you will see the hint text(if specified) and the label text will be shown in the top left(by default).
I also have used the label style parameter which is used to style text label text. It takes the text style like it took in the hint style parameter. I want you to use other properties of text style to give more decoration to label text.

Example 1.4: label parameter

label: Text('This is also a label')
label parameter textformfield
label style field
The parameter label takes a widget. It works the same as label text but the difference is that in labelText we can pass only a string while in label parameter we can pass any Flutter widget. For demonstration, we passed it a Flutter text widget.
The labelStyle also give style to the label as well so you can use it. You can see in the second image that there is some size difference as well because we gave it a bigger size using textstyle.
Make sure that you can use only labelText or label parameter at one time, if you tried to use both at one textformfield widget then you will face an error.

Example 1.5: errorText and errorStyle parameter

  errorText: 'This is error text',
  errorStyle:
          TextStyle(
              fontStyle: FontStyle.italic, 
              fontSize: 13)
flutter errortext textformfield
This errorText parameter is actually used while validating the textformfield widget. For instance, a user has to input a valid email. In case, the user did some mistake or the email format is not correct then error text will appear. We can handle it logically using Flutter textformfield validator or other logic as well. See example 5 to understand how the validator of Flutter textformfield works.
The errorStyle parameter is used to design the error text. It takes a text style like it does for the hint text and label text. For the sake of demonstration, I make its font style italic and specified its font size as well.
By default, the color of error text is red, but you can change it using text style as well.

Example 1.6: error parameter

error: Container(
      height: 11,
      width: 41,
      color: Colors.red,
                  ),
error textformfield
The error parameter will show in place where the error text is shown. It takes a Flutter widgets so it’s up to you whatever widget you want to pass. I passed a Flutter container widget to it just to show you how it works.
If you pass a text widget to it then you can specify its decoration using error style as well. You can also use the style parameter of the Text widget as well to specify its design.
Make sure to use only errorText or error at a time in one Flutter textformfield widget. If you use both, then a code error will occur.

Example 1.7: border parameter of textformfield

border: InputBorder.none
flutter textformfield border
The parameter border can be used to customize the border. If you want to remove the underline border then just use the none property of InputBorder class. In the above image, we can see that the underline border is gone.

Example 1.8: enabledBorder of Flutter textformfield widget

enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(21),
          borderSide: BorderSide(
          color: Colors.blue,
          width: 1.5,
                    ),
                  )
enabled border flutter textformfield
The enabledBorder is the border of textformfield when its not focused. It can take underline input border as well, but we’ve passed it outline input border which covers all the sides. The border side is used to customize the color of border, its width and more.
Its borderRadius parameter is used to set the circular shape of the edges of border. The circular method sets all the edges to same circular shape. You can use its other methods as well like only(), all(), vertical(), horizontal() etc. I want you to explore its properties and apply them to learn more about how they work.
Also, you can use the copyWith() method if you want give a different property to one or more edges. You can use it like this:
 borderRadius: BorderRadius.circular(11).copyWith(topLeft: Radius.circular(0))
enabled border flutter textformfield copy with
Here you can see that the top left edge has no circular radius as we have set it to 0. Same you can do for all the other edges as well using copy with method.

Example 1.9: focusedBorder of textformfield Flutter

focusedBorder: UnderlineInputBorder(
     borderSide: BorderSide(
      color: Colors.orange,
      width: 4,
           ),
           )
focusedborder flutter textformfield
The focusedBorder as the name suggests, its the border that is visible when the text form field is focused. You can pass outline input border to it as well but to make things different, I have passed it an underline input border. I have given its border side some color and width customization. Your assignment is to customize it even more by using its parameters.
Keep in mind that even if you pass input border none to the border parameter, still these enabled and focused border will be visible if you had customized them.

Example 1.10: prefixIcon of textformfield Flutter

prefixIcon: Icon(Icons.email)

textformfield flutter prefix icon

This prefixIcon parameter takes a widget and its role is to show an icon at the starting means left position of Flutter textformfield as shown in the above image. You can pass it any widget you like, for instance, a Flutter dropdown, Flutter container or some other widget but for this example, I have passed it an email icon using Flutter icon widget. You can easily change the icon color, size of icon and more.

Example 1.11: suffixIcon parameter

suffixIcon: Icon(Icons.visibility)
flutter text form field suffix icon

The suffix icon also takes a widget and it shows that widget in the end/right side in the textformfield widget. In that example too, I have passed it an icon widget but you can pass any widget that meet your app requirements.

Example 1.12: filled parameter

filled: true
flutter textformfield background color default
The parameter ‘filled’ is by default set to false and its used to specify whether to show the Flutter textformfield background color or not. I set it to true and now you can see the default background color of this textformfield.
The line at the bottom is the default underline border of textformfield, you can remove it too or you can use the outline input border, it totally depends on your Flutter app requirements.

Example 1.13: fillColor parameter

fillColor: Colors.blue

flutter textformfield background color change

If you want to change the Flutter textformfield background color, then use the filledColor parameter of input decoration class. It takes a color so for demonstration, I’ve passed it a blue color.

Keep in mind that in order for this color to show as the background color of textformfield, you have to make the filled parameter true, if its’ false then the background color won’t be visible.

Example 2: autoFocus parameter

 autofocus: true
The auto focus of this field is used to automatically focus it. It takes a Boolean value and by default it has the value ‘false’.
We can see in the syntax section in which the first image shows a text form field that is not focused but in the second image we tapped on it and focus it so we can write something in it.
So in case you want the field to be focused automatically when the screen loads then set the autoFocus of textformfield to true.

Example 3: focusNode parameter of Flutter Textformfield

FocusNode _focusNode = FocusNode();
Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

          Padding(
            padding: EdgeInsets.all(11),
            child: TextFormField(
              focusNode: _focusNode,
            ),
          ),

          Padding(
            padding: EdgeInsets.all(11),
            child: TextFormField(),
          ),

          MaterialButton(
            onPressed: () {
              _focusNode.requestFocus();
            },
            child: Text('Focus first field'),
          )
        ],
      ),
flutter textformfield focusNode
See below explanation:
  1. The parameter focusNode can be used to specify when to focus which text form field as it can manage the focus state of this field or other fields that have the focus property.
  2. First we created an instance(_focusNode) of the Focus Node class, then assigns it to just the first textformfield widget. We created 2 fields to show you that the focus of first will change programatically. You can use multiple focus nodes and assigns them to different text form fields as well.
  3. We created a simple material button as well and inside it we call the request focus method of the focus node object. This will shift the focus to the field and make it focused. In our case, we have passed the ‘_focusNode’ to the focus node parameter.
  4. To demonstrate it, first both fields were unfocused, but when we click on the material button widget then request focus was called and as a result the field with ‘_focusNode’ got focused.

Example 4: canRequestFocus of Textformfield Flutter

canRequestFocus: false
  • This parameter is used to prevent the specific textformfield to gain focus. It takes a Bool value and by default, its true.
  • I set it to false and now when I press the material button to get it focused or even tapping on this field then still it didn’t get focused. So set it to false for any field you don’t want to get focused.
  • Even autoFocus won’t make it focused if the canRequestFocus is set to false for that field.

Example 5: validator of Flutter textformfield

In this example, we’ll understand how to validate a password field using Flutter textformfield validator. See below steps:

Step 1: Create Global Key
final _formKey = GlobalKey<FormState>();

I first created a global key that will identify the specific form in which we’ll work. It’ll fetch the state of that form so we can see validation.

Step 2: Form Widget
Form(
  key: _formKey,
  child: // the textformfield will come here
)

We have to use the form widget and pass the global key specified above to its key parameter. This will manage the state of fields so you have to wrap the fields with it. In our case its text form field widget. If you have multiple fields then just pass a column widget to the child parameter of form widget and specify all the fields there.

Step 3: logic in Flutter textformfield validator
Form(
     key: _formKey,
          child: TextFormField(
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Password cannot be empty';
              }
              if (value.length < 8) {
                return 'Password must be at least 8 characters long';
              }
              if (!RegExp(r'[!@#$%^&*(),.?":{}|<>]').hasMatch(value)) {
                return 'Password must contain at least one special character';
              }
              if (!RegExp(r'\d').hasMatch(value)) {
                return 'Password must contain at least one numeric digit';
              }
              return null; // Password is valid
            },
          ),
        ),
Here I have used the validator parameter which takes a function with one parameter. This parameter holds the current value of the textformfield.
This value will be checked with each condition I specified inside the function body. If any of the condition is not validated then the specified error string will be returned. If all the conditions are valid, then it will return null which means the field is valid.
Step 4: trigger the validation using button
 ElevatedButton(
        onPressed: () {
            if (_formKey.currentState!.validate()) {
               ScaffoldMessenger.of(context).showSnackBar(
                   SnackBar(content: Text('Data is valid')),
                  );
                }
              },
              child: Text('Submit'),
            )
Here I used a simple Flutter elevated button widget and inside its onPressed functin body, I specified the code. By using the _formKey we will use the current state and then its validate method. It’ll trigger the validator function of all the fields inside the form widget(in our case we have only one field). It’ll see the validation status, if true then it’ll show a simple Flutter snackbar widget(you can do any actions you like) and if not then it’ll show a error text.
Step 5: Test the Validator

flutter textformfield validator

validator flutter textformfield

I first pass it an invalid data that doesnot meet the condition I specified inside the function passed to the validator parameter and pressed the button as seen in the first image.

In the second one, I gave it the valid string which meets the conditions and therefore the field is validated. As a result, a snackbar is shown on the screen.

Example 6: style parameter

The Flutter textformfield style parameter is used to style the input data that is entered by the user. For instance, when a user click on the textformfield and enter something then we can decorate that data using the style parameter of textformfield widget.

Let’s first see how the data will look by default.

Example 6.1: Default style

flutter textformfield textstyle default

Example 6.2: Custom style
style: TextStyle(color: Colors.pinkAccent, fontSize: 21)

flutter textformfield style custom

You can see that the style parameter takes a text style. So, for demonstration, I just changes the color of text and its size. You can play with other properties of textstyle as well to decorate your entered data of textformfield more.

Conclusion

So now you have a detailed practical knowledge of how to implement a Flutter textformfield widget and how to properly customize its design. Do comment if you have any questions or problems related to this Flutter widget.

Thank you and stay tuned for more info on Flutter app development.

Leave a Comment

Your email address will not be published. Required fields are marked *