Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide keyboard on scroll in Flutter

Tags:

flutter

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.

like image 889
Erlend Avatar asked Mar 22 '19 19:03

Erlend


People also ask

When should we use a resizeToAvoidBottomInset?

Use resizeToAvoidBottomInset to specify if the body should resize when the keyboard appears.

How do I hide the virtual keyboard in flutter?

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.

How to hide on-screen keyboard when the user taps outside 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.

How to remove focus from the current node in flutter?

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.

How to hide the keyboard when the focus is inside?

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


1 Answers

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(...),
);
like image 145
Arsen Ghazaryan Avatar answered Oct 10 '22 08:10

Arsen Ghazaryan