Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you change the value inside of a textfield flutter?

Tags:

flutter

dart

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?

like image 223
Daniel Avatar asked Jul 01 '18 21:07

Daniel


People also ask

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.


2 Answers

Simply change the text property

    TextField(       controller: txt,     ),     RaisedButton(onPressed: () {         txt.text = "My Stringt";     }), 

while txt is just a TextEditingController

  var txt = TextEditingController(); 
like image 158
Raouf Rahiche Avatar answered Sep 22 '22 12:09

Raouf Rahiche


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.

like image 30
rfarias Avatar answered Sep 21 '22 12:09

rfarias