How To Implement Textfield In Flutter?

Learn via video courses
Topics Covered

The TextField widget in Flutter is an essential UI component for input, allowing users to enter alphanumeric data such as names, passwords, and addresses. It is a versatile graphical user interface control element programmable for various applications. By default, it features an underline decoration, but developers can enhance it with attributes like labels, icons, inline hint text, and error text using InputDecoration.

 Just by writing TextField(), we get this view.

intro-image

How to Use TextField Widget in the Flutter App?

To use the flutter textfield widget, you just have to write TextField() and pass the required properties according to your needs. You can fully customise your widget by width, height, border colour, without border, label, hint, input type, making fields compulsory, styling text to borders, etc. 

There are two flutter textfields-

  1. TextField - This is normally used everywhere and you do not want to validate the user input.
  2. TextFormField - This is used when you want to validate the inputs from the user and want to show an error message and a red border with the validator property.

Common Attributes Used with the TextField Widget

1. decoration
This is the very main property of flutter textfields which helps in styling a lot of things like borders, hint style, content padding,icons etc. It returns InputDecoration(), which has properties like -

  •  label- It is an optional widget that describes the input field.
  •  floatingLabelBehavior-This means how the label widget should be displayed.
  •  suffixIcon- This returns a widget that appears after editable text inside the decoration.
  •  prefixIcon-This returns a widget that appears before editable text inside decoration only.

2. border
It returns OutlineInputBorder(), and you can pass the border width, colour, and radius of the borders.

3. labelText It is optional and describes the flutter textfield and is controlled by the floatingLabelBehavior property.

4. hintText What hint can we give to users, like, writing a name, writing an email, writing a phone etc? We can also style the hint using the hintStyle property. 

5. icon This returns a widget which shows before the input field and outside of the decoration's container.

Below is the code for all these properties to help you understand more about their usage.

name-1 name-2

How to Retrieve the Value of a TextField?

  1. onChanged method

This method of flutter textfield is triggered when textfield's content changes. It helps in performing various actions in response, like updating the UI, validating user input, starting API calls, and many more. Remember to wrap your textfield in a Widget to use the setState method to update the value. The callback function receives a single value, which is the updated value of the text field.

  1. Using Controllers

To get the value entered by a user, you have to create a TextEditingController and pass this value to the controller property of TextField or TextFormField. This TextEditingController class helps in managing the text field's value, and selection, and performs various operations on the text.

Let's understand the flutter textfield's controllers through some steps and code.

  1. Create a TextEditingController instance first outside the build method.
  1. Now pass the instance of TextEditingController to the controller property of the flutter textfield.
  1. To retrieve the controller's value, you can use the text property of TextEditingController.
  1. To clear the controller's value, you can use the clear method and this will clear the user-entered data.
  1. You can also observe and respond to the flutter textfield's value by adding a listener to the TextEditingController.

Note 📝:

Always dispose of your TextEditingControllers when you are finished using the controllers in the dispose() method of flutter.

Advanced TextField Functionality

  1. How to make TextField expandable?

To expand the flutter textfield, you have to pass some fields. You have to pass minLines and maxLines property. You can also pass the maxLength property for counting the length of characters.

Expandable Textfield

  1. How to control the size of TextField value?

Giving size to a flutter textfield means what width we should give to our textfield. You can wrap the widget with the SizedBox() widget and pass width inside sizedBox.

sizebox

  1. How to obscure text field value?

Obscure means we have to hide our text so that one can not see what we have written like in password, OTP and many other things. To do this, you just have to pass the bool value to the obscure property. True means the text is hidden and False is for showing the text.

sizebox-1

  1. Implementing autocomplete suggestions with the TextField widget

To implement this functionality in Flutter textfield, you have to follow some steps to get the results.

  • Define TextEditingController , a list of items you want to select an item from and the filtered suggestions as you start typing something.
  • Add a listener to the TextEditingController and pass a method to get the filtered suggestions as the user starts typing and also dispose of the controller value inside dispose of the method.
  • Then we display the filtered suggestions in ListView.builder and in the onTap method, we update the flutter Texfield's text and clear the suggestions.

flutter-textfield

flutter-textfield-1

  1. Adding error handling for incorrect user input

TextFormField Widget

For this, we use the TextFormField widget of Flutter. There is a validator property of this widget which validates the user input and displays an error text or error widget if the input is wrong.

  • Create a TextEditingController and a GlobalKey to be used in the widgets.
  • Wrap the flutter text field in the Form widget and pass the formKey inside the key property to identify the widget.
  • Then on the onTap function of the button, validate the user input on the current state of formKey and pass the error message or error border if the input is wrong.

Textformfield

Handling Keyboard Interactions

1. We can show different actions for the keyboard when the flutter textfield is focussed. We can pass different actions to textInputAction like -

  • TextInputAction.done

textInputAction-done

  • TextInputAction.next

textinputaction-next

  • TextInputAction.send and many more

textinputaction-send

2. When we enter some data in the flutter textfield, the keyboard persists on the screen. To dismiss the keyboard, you have to touch anywhere on the screen and the keyboard will dismiss. This is achieved by - Wrap your Scaffold() in GestureDetector() and unfocus the FocusScope on tap.

Best Practices for TextField

  1. Try using TextFormField instead of TextField as it is the advanced version of flutter textfields.

  2. Try to wrap your base widget like Scaffold in GestureDetector and pass FoucusScope to unfocus on the tap action as shown in the above section of the "Handling Keyboard Interactions" topic.

  3. In sign-up forms or where many flutter textfields are used in a column, we see an overflow error. To avoid this, we should always wrap our textfield or column (containing multiple textfields) in the SingleChildScrollView widget. 

overflow-problem

  1. The use of flutter textfields is widespread and is used everywhere on almost all screens. To use it make a common class and import and use it at the required places. Below is an example to understand more.

  • This is the commontextfield.dart class where all the properties are defined to pass the dynamic data inside these fields according to our needs.
  • We are going to use the above class like this where we need to use the flutter textfields.

Define a TextEditingController variable on top and pass it inside the class as shown below.

Example Application

Below is the example of using flutter textfield with its various functionalities.

  1. main.dart - We will call TextFieldDemo() class from here.
  1. texfield.dart - This file contains both types of textfields and you will see their usage. Most of the properties are already discussed in this article and we will discover some more in this example.
  • If enabled: false, then you cannot interact with the flutter textfield and you will have to wrap the widget with GestureDetector to get the controller's value. You will not be able to see the cursor as shown in the third textfield. Generally used, when you have to select some date or time.

textfields

Checkout the code here - https://github.com/riyatyagi99/blogs/blob/main/blog/lib/textfield.dart

Conclusion

  1. If you want to validate, then use TextFormField and use the validator property of it.
  2. We make a common class for flutter textfields, as they are used in almost all screens. This reduces redundancy and makes code clean and readable.
  3. By default, flutter textfields do not contain borders; you need to pass the border property inside the decoration property.
  4. You can expand the flutter textfield by passing the minLines and maxLines properties.
  5. You can retrieve the current value of input by calling the onChanged() fun callback and by TextEditingController() also.
  6. To get the type of keyboard, use keyboardType and for action button of keyboard use textInputAction.
  7. All other properties discussed in the article that are commonly used and serve the purpose.