Paavanan Vellan
Paavanan Vellan

Reputation: 91

How to prevent back button from dismissing the keyboard in flutter?

I want to set the keyboard to be always opened in the chat page and should not be dismissable by the back button.

The WillPopScope() widget is only preventing the back button from navigating back to the previous page however is still dismissing the keyboard. I am getting the keyboard opened initially via by setting autofocus = true in the textformfield so the only issue I am facing is on preventing the dismissal of the keyboard.

I have looked upon multiple questions in Stack however could not find a suitable solution to this issue. I have been searching for the answer for over 2 months now and hope someone is able to assist me with this issue.

UPDATE:

I did the following change to my heightofdevice where I subtracted the MediaQuery.of(context).viewInsets.bottom and now the transition of the keyboard is better.

I realised the previous method of me trying to fix the keyboard and preventing it from being dismissed had too many fixes to be done on a native level using Java or Kotlin for Android. I initially wanted to fix the keyboard as the transition was poor but with the following method, the transition is better now but there are still room for improvement.

var heightStatusBar = MediaQuery.of(context).padding.top;
var bottom = MediaQuery.of(context).viewInsets.bottom;
widthofdevice = MediaQuery.of(context).size.width;
heightofdevice =(MediaQuery.of(context).size.height) - 
heightStatusBar - bottom;

Upvotes: 8

Views: 1950

Answers (1)

Lucas Bersot
Lucas Bersot

Reputation: 11

The problem is that when the keyboard is opened and the user press the Android Backbutton, the app doesn't change the proper Focus of the keyboard, that is, even if it closes the keyboard, the focus continue as True... With this, the next tap on the textfield to open again the keyboard, the focus is true and the flutter retrieve the information that it already is open and doesn't do anything.

To fix this, you can wrap your tap of the TextField using a GestureDetector and use a combine Focus and viewInsets validation.

void _onFocus() {
    if (_focusNode.hasFocus && MediaQuery.of(context).viewInsets.bottom == 0) {
     _focusNode.unfocus();
     Future.delayed(const Duration(microseconds: 1), 
       () => _focusNode.requestFocus());
} else {
  _focusNode.requestFocus();
}
}

With this, if the user press the backbitten to close the keyboard and press on the TextField to open again, this validation will fail in MediaQuery.viewInsets and it will update the real status of Focus.

Upvotes: 0

Related Questions