我想隐藏SingleChildScrollView
带有焦点的滚动键盘TextFormField
。我NotificationListener<ScrollNotification>
在的顶部添加SingleChildScrollView
,并收听ScrollStartNotification
。然后FocusScope.of(context).requestFocus(FocusNode())
,我打电话隐藏键盘。
当TextFormField
位于屏幕底部时,会出现问题。当我单击它并获得焦点时,键盘出现并向上移动SingleChildScrollView
,这再次触发ScrollStartNotification
并隐藏了键盘。
Ton*_*ado 16
该ScrollView
控件现在有一个keyboardDismissBehavior
属性,你可以使用这个目的。该属性由ListView
、GridView
和继承CustomScrollView
。
该属性默认为,ScrollViewKeyboardDismissBehavior.manual
但可以更改为ScrollViewKeyboardDismissBehavior.onDrag
。
https://api.flutter.dev/flutter/widgets/ScrollView/keyboardDismissBehavior.html
例子
ListView.builder(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text('Item ${index + 1}'),
);
},
)
Run Code Online (Sandbox Code Playgroud)
至少在撰写本文时,该属性尚未通过CustomScrollView
Flutter 稳定分支传递给其父级,但是添加此属性的拉取请求已于 2020 年 9 月 21 日合并到 master 中,并且可能很快就会提供.
而不是使用NotificationListener,将您的SingleChildScrollView包裹在GestureDetector内,然后像这样关闭键盘:
GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) {
FocusScope.of(context).requestFocus(FocusNode());
},
child: SingleChildScrollView(...),
);
Run Code Online (Sandbox Code Playgroud)
小智 5
我们创建了这个简单的小部件。将您的可滚动视图包装在这个小部件中,您就完成了。
/// 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,
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
856 次 |
最近记录: |