I would like to hide the keyboard on scrolling a SingleChildScrollView
with a focused TextFormField
.
I added a NotificationListener<ScrollNotification>
on top of the SingleChildScrollView
, and listen for the ScrollStartNotification
. I then call FocusScope.of(context).requestFocus(FocusNode())
to hide the keyboard.
The problem occur when the TextFormField
is at the bottom of the screen. When i click it, it gets focus, the keyboard appears and moves the SingleChildScrollView
up, which again fires the ScrollStartNotification
and hides the keyboard.
Use resizeToAvoidBottomInset to specify if the body should resize when the keyboard appears.
Hide Keyboard by Changing Focus When a user taps on a text field, Flutter automatically changes the current focus to the tapped text field. At that time, the virtual keyboard will be shown so that the user can type on the text field.
That's how to hide the on-screen keyboard when the user taps outside a text field. You need to remove the focus from the text field when the user taps outside a text field which can be done with the help of GestureDetector or Listener.
If it doesn't, we call unfocus () on the current node to remove focus and trigger the keyboard to dismiss. If you attempt to unfocus () a node that currently has the primary focus, Flutter will throw an exception.
If the focus is inside a webview, keyboard open from another screen or any other then use the below way to hide the keyboard This worked better than the solution to add FocusScope.of (context).unfocus () as that solution put me into a loop of the keyboard being shown and hidden
Instead of doing with NotificationListener wrap your SingleChildScrollView inside GestureDetector and dismiss the keyboard like this:
GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) {
FocusScope.of(context).requestFocus(FocusNode());
},
child: SingleChildScrollView(...),
);
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