Flutter TextEditingController class for text fields
TextEditingController
can be used with the TextFormField
widget to add some good features that we are going to discuss below. It has some interesting properties-
text: Contains the value entered in the TextField.
clear(): this method can be used to clear the value inside TextFIeld
addListener(): calls a Closure function when TextFIeld changes. The function is provided as an argument.
dispose(): It discards all the resources used by the TextEditingController’s object after the Widget is removed from the widget Tree
Listen to input values
This is same as the onChange
property and either one can be used. The onChange
is easier in many cases but here let’s see how we can achieve the same using TextEditingController’s notifyListeners() method
First, Create a TextEditingController object.
final myController = TextEditingController();
Then, Add the controller to a TextField
TextField(
controller: myController,
);
Create a function to be invoked when the TextField values change(just like onChange)
_printLatestValue() {
print(“Second text field: ${myController.text}”);
}
Notify about changes to TextField using notifyListeners()
myController.addListener(_printLatestValue);
This will call the _printLatestValue
function which will print the values inside the TextField which can be accessed using myController.text
property.
Set a default value to the Input
It comes in handy when you pass some value from some other calling widget to the form and want to display that value inside Textfield when the form loads. You can use the Widget’s constructor to intialize the value of the TextField using the TextEditingController.
class _MyFormClass extends StatefulWidget{
// Create the object befor the Constructor.
final myController = TextEditingController();
_MyFormClass(){ // Set the text property to a value to be displayed
myController.text = 'initial Value'
}
Clear the values of Input field
Suppose you want to clear the TextField value after some validation error or after form submission then you can use the clear() method of the controller
It goes like this-
myController.clear()
You can use this inside any validation construct or onPress of a button.
Don’t forget to clear the memory
Use the despose() method of to free the resources that the TextEditingController
is using so that it doesn’t impact the performance in any way. You can do that in the despose() block of the parent widget of the TextField or form. This also removes the listeners as well.
void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
myController.dispose();
super.dispose();
}
If you like my work consider supporting me
Thanks:)