Rafael Honda
Rafael Honda

Reputation: 227

Flutter set value to a textfield

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.

Upvotes: 9

Views: 21462

Answers (1)

Toma
Toma

Reputation: 2936

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);
}

Upvotes: 24

Related Questions