Hide keyboard on scroll in Flutter
We have created this simple Widget. Wrap your scrollable view in this Widget and you're done.
/// A widget that listens for [ScrollNotification]s bubbling up the tree
/// and close the keyboard on user scroll.
class ScrollKeyboardCloser extends StatelessWidget {
final Widget child;
ScrollKeyboardCloser({@required this.child});
@override
Widget build(BuildContext context) {
return NotificationListener<ScrollNotification>(
onNotification: (scrollNotification) {
if (scrollNotification is UserScrollNotification) {
// close keyboard
FocusScope.of(context).unfocus();
}
return false;
},
child: child,
);
}
}
The ScrollView
widget now has a keyboardDismissBehavior
attribute that you can use for this purpose. The attribute is inherited by ListView
, GridView
and CustomScrollView
.
The attribute defaults to ScrollViewKeyboardDismissBehavior.manual
but can be changed to ScrollViewKeyboardDismissBehavior.onDrag
.
https://api.flutter.dev/flutter/widgets/ScrollView/keyboardDismissBehavior.html
Example
ListView.builder(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text('Item ${index + 1}'),
);
},
)
At least at the time of this writing the attribute is not yet passed on to its parent by CustomScrollView
in the Flutter stable branch, but a pull request to add this attribute has already been merged into master on Sep 21, 2020 and will probably be available soon.
Instead of doing with NotificationListener wrap your SingleChildScrollView inside GestureDetector and dismiss the keyboard like this:
GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) {
FocusScope.of(context).requestFocus(FocusNode());
},
child: SingleChildScrollView(...),
);