Created
August 23, 2021 15:38
-
-
Save fabiancrx/5f78ab7b720d55efdb5a02a241d187ff to your computer and use it in GitHub Desktop.
Dissmiss the keyboard in Flutter when tapped or scrolled
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Removes the current focus and hides the keyboard when | |
/// the user drags or taps this widget. | |
/// | |
/// Place this widget somewhere near the top of your widget | |
/// tree and when the user drags or taps outside of a focused widget, | |
/// the focus will be removed and the keyboard will be hidden. | |
class KeyboardDismiss extends StatelessWidget { | |
final Widget child; | |
final bool dismissOnTap; | |
final bool dismissOnDrag; | |
const KeyboardDismiss({Key? key, required this.child, this.dismissOnTap = true, this.dismissOnDrag = true}) | |
: super(key: key); | |
void _hideKeyboard(BuildContext context) { | |
final currentFocus = FocusScope.of(context); | |
if (!currentFocus.hasPrimaryFocus && currentFocus.hasFocus) { | |
FocusManager.instance.primaryFocus?.unfocus(); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return NotificationListener<ScrollUpdateNotification>( | |
child: GestureDetector( | |
onTap: dismissOnTap | |
? () { | |
_hideKeyboard(context); | |
} | |
: null, | |
child: child), | |
onNotification: (ScrollUpdateNotification notification) { | |
final focusScope = FocusScope.of(context); | |
if (dismissOnDrag && notification.dragDetails != null && focusScope.hasFocus) { | |
focusScope.unfocus(); | |
} | |
return false; | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment