I\'d like to supply an initial value to a text field and redraw it with an empty value to clear the text. What\'s the best approach to do that with Flutter\'s APIs?
If you want to handle multiple TextInput
s as asked by @MRT in the comment to the accepted answer, you can create a function that takes an initial value and returns a TextEditingController
like this:
initialValue(val) {
return TextEditingController(text: val);
}
Then, set this function as the controller for the TextInput
and supply its initial value there like this:
controller: initialValue('Some initial value here....')
You can repeat this for the other TextInput
s.
class _YourClassState extends State<YourClass> {
TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_controller.text = 'Your message';
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: TextFormField(
controller: _controller,
decoration: InputDecoration(labelText: 'Send message...'),
),
);
}
}
inside class,
final usernameController = TextEditingController(text: 'bhanuka');
TextField,
child: new TextField(
controller: usernameController,
...
)
This can be achieved using TextEditingController
.
To have an initial value you can add
TextEditingController _controller = TextEditingController(text: 'initial value');
or
If you are using TextFormField
you have a initialValue
property there. Which basically provides this initialValue
to the controller automatically.
TextEditingController _controller = TextEditingController();
TextFormField(
controller: _controller,
initialValue: 'initial value'
)
To clear the text you can use
_controller.clear()
method.
TextEdittingController _controller = new TextEdittingController(text: "your Text");
or
@override
void initState() {
super.initState();
_Controller.text = "Your Text";
}
I've seen many ways of doing this on here. However I think this is a little more efficient or at least concise than the other answers.
TextField(
controller: TextEditingController(text: "Initial Text here"),
)