Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to clear text field on focus

Tags:

flutter

dart

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(), ...)
like image 436
cubanGuy Avatar asked Jan 29 '19 19:01

cubanGuy


People also ask

How do you Unfocus focus node Flutter?

Try setting focus on the four text fields by selecting them, and then select "UNFOCUS" to see what happens when the current FocusManager. primaryFocus is unfocused. Try pressing the TAB key after unfocusing to see what the next widget chosen is.

What is FocusNode in TextFormField Flutter?

FocusNode basically focuses on the keyboard event. Let's suppose you want to control the TextFormField widget as soon as the user taps on it, then you use FocusNode . So, FocusNode class is basically an object that can be used to obtain keyboard focus and to handle keyboard events.


1 Answers

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, ...);
}
like image 74
creativecreatorormaybenot Avatar answered Oct 08 '22 20:10

creativecreatorormaybenot