I'm new to flutter. I have a project with a list of contacts (name, phone, address), when the user taps on contact I'm sending him to an edit form, I want to fill the form with the contact data. I'm using a Textfield for the inputs and getting data through widgets using for example: widget.contact.data['name']. I couldn't find any answers for this problem.
Declare TextEditingController. supply controller to the TextField. user controller's text property to change the value of the textField.
By default, a TextField is decorated with an underline. You can add a label, icon, inline hint text, and error text by supplying an InputDecoration as the decoration property of the TextField . To remove the decoration entirely (including the underline and the space reserved for the label), set the decoration to null.
There are two ways to access text from a TextField, as shown in Flutter's docs.
The first one is through the onChanged callback, which has a parameter that is the current text.
TextField(
onChanged: (text) {
// do what you want with the text
},
);
For more advanced handling of the text, including accessing it from outside the build()
method, you can use TextEditingController.
final _controller = TextEditingController();
Then you can link it to your TextField:
TextField(
// other parameters
controller: _controller,
);
Don't forget to dispose it!
@override
void dispose() {
// other dispose methods
_controller.dispose();
super.dispose();
}
Now you can either set or get the text by either accessing the value of _controller.text
or modifying it. For example:
Getting: print(_controller.text);
Setting: _controller.text = 'newText' // now the TextField will have 'newText' written
Or you can listen to changes using addListener
, so whenever the text is updated, a function of your choice will be called:
@override
void initState() {
super.initState();
_controller.addListener(_handleText);
// other code here
}
_handleText() {
// do what you want with the text, for example:
print(_controller.text);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With