How do I supply an initial value to a text field?

前端 未结 10 877
南笙
南笙 2021-01-30 12:15

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?

10条回答
  •  被撕碎了的回忆
    2021-01-30 12:35

    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.

提交回复
热议问题