Flutter Tips: Dismiss Keyboard When Tapping Out Of TextFiled
One of the most common User Experience (UX) issues in the Mobile Development track, is when you have input filed and the user finishes typing inside it and need to close the keyboard to continue with another thing, he/she can’t do simply with tapping out of input instead he/she forced to press back button, and this work against UX principles, you need to make using of your application done with familiar behavior for users, not forcing them to follow your rules this increase useability of your application.
use-case with Dart/Flutter
If you have TextFiled or any input with some decorations like that:
when the user clicks on it and finished typing and want to dismiss the keyboard he/she can do this only by press the back button, and this is the default behavior of TextFiled or any input in Flutter or even the native android or ios.
Solve the issue
to solve the problem we need to know first what cause this.
every TextFiled has its own Focus Node.
Focus Node: An object that can be used by a stateful widget to obtain the keyboard focus and to handle keyboard events.
TextFiled request the focus When you tap on it, and then show the keyboard, the problem if you tap out of it, it still has the focus, so we need to remove focus from it or assign it to another widget. To do that you need to add a function run whenever the user taps on Scaffold -because it represents the entire screen-.
And to add this functionality, we need to wrap Scaffold with another widget called Gesture Detector.
Gesture Detector: A widget that detects gestures, Attempts to recognize gestures that correspond to its non-null callbacks.
If this widget has a child, it defers to that child for its sizing behavior. If it does not have a child, it grows to fit the parent instead.
Gesture Detector has a lot of useful Properties, such that onTap Property which assign function to it and run whenever we tap on Gesture Detector child (Scaffold), inside this function we need to request the focus to another FocusNode to take it form any input filed and this done by using Focus Scope of our context and request the Focus of this context to another widget’s FocusNode, but here we don’t interest to assign focus to any other widget so simply we pass a new FocusNode, if you need to give focus to another widget you need to pre-create FocusNode and assign it to this widget.
By this, you can dismiss the keyboard whenever you tap out of TextFiled.