Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter set value to a textfield

Tags:

flutter

dart

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.

like image 346
Rafael Honda Avatar asked Mar 04 '19 16:03

Rafael Honda


People also ask

How do you assign a value to a TextField in flutter?

Declare TextEditingController. supply controller to the TextField. user controller's text property to change the value of the textField.

How do you customize a TextField in flutter?

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.


1 Answers

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);
}
like image 88
Toma Avatar answered Oct 03 '22 02:10

Toma