Close on-screen keyboard, and THEN navigate to new screen (to ensure keyboard doesn't infringe on size of new screen)

1.7k Views Asked by At

Title sums it up well. In Flutter, you can close the keyboard by removing the focus from it:

  FocusScope.of(context).unfocus();

And you can navigate to a new screen like so (many ways, just an example):

Navigator.of(context).pushNamed('routeName');

However, you can't wait for the keyboard to close before navigating to a new screen.

I'd like to do something like this:

await FocusScope.of(context).unfocus();
Navigator.of(context).pushNamed('routeName');

^ This doesn't work because you can't await .unfocus().

or:

FocusScope.of(context).unfocus();
await Future.delayed(const Duration(seconds: 1));
Navigator.of(context).pushNamed('routeName');

^ This doesn't work because you can't use BuildContext across async gaps.

How does one wait for the keyboard to disappear before navigating? Because, currently, closing the keyboard at the same time as navigating means the screen you're navigating to experiences a short period where the on-screen keyboard is inhibiting the new screen from being full size. This looks ugly.

Thanks.

3

There are 3 best solutions below

1
Lakshydeep Vikram Sah On

Whenever you go in new screen run the code below in initState function of new screen. This help you to close the onscreen keyboard whenever you visit new screen.

@override
void initState(){
   FocusScope.of(context).unfocus();
}
0
Nasimi Gun On

Write this in the Scaffold of the next(or prev) screen

resizeToAvoidBottomInset: false
0
Mark Jose Ultra On

Wait for the keyboard to close before navigating.

void goBack() {
   FocusScope.of(context).unfocus();

   ///Wait for the keyboard to close before navigating
   Future.delayed(Duration(milliseconds: 500), () {
       Navigator.of(context).pop();
   });
}