What is Controller
As per the name controller so our basic idea is something is controlled by this property but what? So, the answer is If you have an editable text widget then you need to store the value of that text somewhere. The simplest way is by setting a TextEditingController as the controller of a TextField. The value of the textField is updated with the use of this controller.
How to use the controller with the example:-
We are taking an example to Retrieve the value of a text field that is entered by the user and that value is shown us in the snackbar Let's start with the following steps:
1. Create a TextEditingController
To retrieve the text from the text field entered by the user, we create a TextEditingController and set it to a TextField or TextFormField. TextFormField is also working as TextField which we are discussing more in further blog with detail.
Note: you need to call dispose of the method of the TextEditingController when you have finished using it and not further needed. This ensures that you discard any resources used by the object.
2. Set the TextEditingController to a TextField property controller
Now that you have a TextEditingController, wire it up to a text field using the controller property:
3. Display the current value of the textField in snackbar
After Setting up the TextEditingController to the text field, With the use of the text() method which is provided by the TextEditingController, you can retrieve any kind of value that the user has entered into the textField.
The following code displays the current value of the textField and shows it in Snackbar when the user onPressed on the ElevatedButton button.
Below example code contains all the properties as per discussion :
Nicely explained!
ReplyDeleteThank You
DeleteThis comment has been removed by the author.
ReplyDelete