santosh singh
santosh singh

Reputation: 61

How to set TextFormField dynamically?

I am using flutter and I want to set text (String value) in TextFormField dynamically, means set value over press of a button.

Upvotes: 5

Views: 6802

Answers (2)

Abrham Daniel
Abrham Daniel

Reputation: 49

use TextEditingController. Then assign it to the TextFormField then make use of the controller to assign the new data from wherever you want. If you want initial data assign it some value in the initState() function also use it on a stateful widget. _textEditingController.text = "1";

Upvotes: 5

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126694

You can make use of a StatefulWidget to adjust the initialValue property of your TextFormField.

class TextFieldChanger extends StatefulWidget {
  @override
  _TextFieldChangerState createState() => _TextFieldChangerState();
}

class _TextFieldChangerState extends State<TextFieldChanger> {
  String presetText;

  void _onPressed() {
    setState(() {
      presetText = 'updated text';
    });
  }

  @override
  Widget build(BuildContext context) => Column(children: [
    TextFormField(initialValue: presetText),
    RawMaterialButton(onPressed: _onPressed),
  ]);
}

In setState, I am assigning a new value to presetText and build will be called (with the updated initialValue) because of setState.

Upvotes: 3

Related Questions