I have a TextEditingController
where if a user clicks a button it fills in with information. I can't seem to figure out how to change the text inside of a Textfield
or TextFormField
. Is there a solution?
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.
Simply change the text
property
TextField( controller: txt, ), RaisedButton(onPressed: () { txt.text = "My Stringt"; }),
while txt
is just a TextEditingController
var txt = TextEditingController();
The problem with just setting
_controller.text = "New value";
is that the cursor will be repositioned to the beginning (in material's TextField). Using
_controller.text = "Hello"; _controller.selection = TextSelection.fromPosition( TextPosition(offset: _controller.text.length), ); setState(() {});
is not efficient since it rebuilds the widget more than it's necessary (when setting the text property and when calling setState).
--
I believe the best way is to combine everything into one simple command:
final _newValue = "New value"; _controller.value = TextEditingValue( text: _newValue, selection: TextSelection.fromPosition( TextPosition(offset: _newValue.length), ), );
It works properly for both Material and Cupertino Textfields.
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