简体   繁体   中英

Flutter - How to clear text field on focus

How can I remove all text from a TextFormField on focus? This was very easy in JavaScript: onfocus="this.value=''"; . I don't want to use a button like this:

FlatButton(onPressed: () => _textFieldcontroller.clear(), ...)

You can use FocusNode in combination with a StatefulWidget .

We keep an object of FocusNode in our class:

FocusNode _focusNode;

In the constructor of our TextFormField , we will have to pass _focusNode as a parameter:

TextFormField(focusNode: _focusNode, ...

Now we can add a listener to our FocusNode that will always get called when the focus of our TextFormField updates. In it, we can check whether our FocusNode has focus or not and take action according to that.

_focusNode.addListener(() {
  if (_focusNode.hasFocus) _textFieldController.clear();
});

In a widget:

class ExampleWidget extends StatefulWidget {
  @override
  _ExampleWidgetState createState() => _ExampleWidgetState();
}

class _ExampleWidgetState extends State<ExampleWidget> {
  FocusNode _focusNode;
  TextEditingController _textFieldController;

  @override
  void initState() {
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) _textFieldController.clear();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) => TextFormField(focusNode: _focusNode, controller: _textFieldController, ...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM