Dismiss keyboard on swipe back gesture in Flutter app

Issue

I am trying to dismiss the keyboard when the user swipes from the edge to pop route.

Currently the keyboard doesn’t dismiss until the route is completely gone popped, messing up some of the other pages layout until it dismisses

I did try to use a WillPopScope to determine when the user was going to pop the route, but unfortunately this disables the swipe to pop functionality from iOS or the CupertinoPageRoute.

I just want to find out if there’s anyway I can determine when the user swipes from the edge to pop or taps the back button on the appBar and dismiss the keyboard as they do so.

If possible, I am trying to dismiss keyboard as soon as they start swiping to pop, as it happens in many apps.

I am attaching attaching a gif showing the effect I’m trying to achieve.

Swipe to pop hides keyboard

Solution

You need to create a custom class extending NavigatorObserver, and pass an instance of it to the navigatorObservers property of your MaterialApp or CupertinoApp.

Within that custom class, you can override didStartUserGesture and didStopUserGesture, which will be called when the swipe gesture starts/ends. This should allow you to achieve the behavior you are looking for. Note that didStartUserGesture indicates the current route as well as the previous route, based on which you could add logic to determine whether the keyboard should be dismissed or not.

Answered By – Ovidiu

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *