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(), ...)
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.
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.
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, ...);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With