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

Viewed 35

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.

1 Answers

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();
}
Related