Textfield in Flutter
Overview
Textfield is one of the most interactive widgets in the Flutter SDK which takes a little bit of the user's time to complete the action. So making sure that the user experience, while typing, is of the utmost importance, since it can make or break your app.
In this article, we are going to build different types to understand the various nuances of Textfield in Flutter.
Introduction
TextField in Flutter is a Stateful Widget that allows for capturing user input which we can use to manipulate for further needs. TextField comes with a rich set of public APIs that offer a lot of convenient methods to style and decorate them.
We can design textfields to even add more widgets in prefixes and suffixes to utilize their functionalities. For example, a password textfield has a visibility icon in the suffix that hides the password and shows it when clicked.
Creating a Basic TextField
You can create a very basic textfield in Flutter in just 1 line. This is how you do it:
And that's it. Internally, TextField is a Stateful widget that handles its own lifecycle and data changes and provides those changes in the callbacks. You can use a hardware keyboard or soft keyboard for input into this textfield.
This is how the code looks now:
Creating a Basic TextFormField
Many a time you would want to create a form and want users to enter data following some guidelines and run validations on them. For these situations, you can use a TextFormField. It is a wrapper around it that offers other convenience methods like validator and onSaved callback.
The validator callback asks for a nullable string in return. If all your validations pass, you can send back null else, an error string that will reflect in the UI.
Customizing TextField
When you work on a project, you are often asked to follow the design guidelines provided by the Design team. This is when you are tasked with customizing the textfield in Flutter.
Styling a textfield in Flutter is very easy. You can add multiple decorations over it and come up with a brand new-looking textfield as required by the design specs.
Styling a Text Field
You can change every aspect of textfield you are working with, including but not limited to the internal paddings, prefix and suffix icons, borders, and much more.
By default, Flutter provides an underline with the theme color. You could change borders this way:
Here, we're requesting Flutter to present the textfield in such a way that when the text field is not focused, we see a grey colour border and when focused, the border should turn to teal. Below is how it looks:
By default, Flutter provides you with UnderlineInputBorder like this:
Bonus Content: How to use icons in TextFields? Flutter provides us with a way to add prefix and suffix widgets to the textfield with prefix, prefixIcon, and suffix and suffixIcon. Here is how you can do it:
What are we doing here?
- We created a text field and assigned a text editing controller to it.
- We added some basic styling like border and text color to make the widget appealing.
- We added a phone icon in front of the textfield and a suffixIcon with GestureDetector to erase the text on the textfield when clicked.
This is how it looks:
Changing Text Colour
Changing the text color of TextField in Flutter can be done using the style variable.
Adding Hint Text
Hint text in the text field is used when you want to give your users some extra information about what goes into the text field. Example: when you're creating a username, you want to denote what that text field does. You can customise the color, style and font. The hint can be added like this:
When using hints, you can also use labels which provide a nice default animation when clicked and transforms hint to label.
Adding Multi-line Support
Adding multiline support in textfield in Flutter is very easy. There is a property called maxLines. The default value is 1. You can set it to null and then the cursor moves to the next line when one finishes.
you could also set max lines to a number to limit the number of lines.
Pre-populating Text
When you want to start your UI which has textfields, but you also want to have some data already filled in, you will have to use the controller for setting the value to the textfield in Flutter.
You create a TextEditingController and assign a String value to it that you want the textfield to have. And then assign that controller to your textfield, and that is it. All done.
One other way could be using TextFormField and using its initialValue parameter.
Here are more ways to style your textfield.
Reading Input Value
When the user starts typing into the textfield in Flutter, we want to either manipulate the data or run some validation when the user is typing. For those cases, users can use either of these two options.
- onChanged Callback
- controller.addListener
When you don't want to use the controller, you can use the onChanged callback inside the TextView in Flutter which is called every time user changes data inside the textfield.
When you have a controller, you can attach a listener to it in initState and use the controller.text property to get the current text inside the text field.
There are two more callbacks provided in the textfield in Flutter. These are:
- onSubmitted
- onEditingComplete
Changing Keyboards Based on Input Type
You might want to change the keyboard that is required for inputting data into the textfield. When you want to add a phone number or you want to add an email address, you'd want a more customized experience. For this use case, you can use keyboardType.
There are multiple options provided by Flutter in the public API:
- TextInputType.text (Normal complete keyboard)
- TextInputType.number (A numerical keyboard)
- TextInputType.emailAddress (Normal keyboard with an “@”)
- TextInputType.DateTime (Numerical keyboard with a “/” and “:”)
- TextInputType.numberWithOptions (Numerical keyboard with options to enable signed and decimal mode)
- TextInputType.multiline (Optimises for multi-line information)
Converting a Normal Text Field to a Password Field
Converting a default textfield in Flutter to a password field is fairly easy. Flutter provides us with a decent public API that enables developers to obscure text. You can even customise what character is used for obscuring the text.
Restricting the Number of Characters
Restricting the number of characters comes with a single line of code. You can specify the number of characters and Flutter will take care of everything. It will even provide you with a character count text.
Restricting and Allowing Input Values
TextInputFormatter classes provide a way to restrict or allow the values that can go into the textfield in Flutter.
You can either use a regular expression to allow or deny a value or use a default filtering text input formatted like this.
Other ways you can use are:
You can also use a combination of 2 or more InputFormatters.
Validating Input With Error Messages
When we're building forms like sign-in or sign-up and want to make sure that the user data is correct before sending the data to the server.
For validating, you can either use TextFormField and use its validator or a textfield in Flutter.
This is how it looks right now:
What are we doing here?
-
We create a GlobalKey with FormState which we will later use in the code to validate the code
-
We create a Form widget and assign it the form key that we created in the previous step.
-
We create a TextFormField and add a validator and define what conditions need to be met.
-
On press of the submit button, we want to make sure that the error is shown if the validate function returns false.
-
Dispose controllers: When using TextEditingControllers, make sure you dispose them after overriding the dispose method to avoid any leaks and errors.
-
Abstract TextFields: When we build a project, textfields are used in a lot of places and sometimes the same code is used everywhere. You should create your textfield in a stateful widget and try and add some functions for example, onChange callbacks to ensure a common API to be used everywhere.
-
Avoid Long Forms: When building out applications, it is easy to complicate UI with long forms but that is bad UX. Try and make forms shorter by adding some steps and visual progress to make it easy and appealing.
-
Use TextFormFields: When you want to validate input in a form, try and use TextFormField because it provides some convenient methods to validate and update the User Interface.
Conclusion
Textfields allow users to input data into the application. In this article we covered them in great detail and talked about different nuances like these:
-
In this article we started with creating a basic textfield in Flutter and styled the textfields with various options that are provided by the TextField API.
-
We understood how to read the data input from the textfield while the data is changing and when the user has submitted the form.
-
We restricted the content that can go into the textfield with the help of InputFormatters using Regex and maxLength variables.
-
We also created a password textfield with which we were able to obscure the text from the user.
-
We also learnt how to validate the input data when a user presses the submit button. This validation was done using TextFormField and validator.