I would like to hide the keyboard on scrolling a SingleChildScrollView
with a focused TextFormField
.
I added a NotificationListener<ScrollNotification>
on top of the SingleChildScrollView
, and listen for the ScrollStartNotification
. I then call FocusScope.of(context).requestFocus(FocusNode())
to hide the keyboard.
The problem occur when the TextFormField
is at the bottom of the screen. When i click it, it gets focus, the keyboard appears and moves the SingleChildScrollView
up, which again fires the ScrollStartNotification
and hides the keyboard.
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.