老孟导读:为什么要实现点击空白处隐藏键盘?因为这是 iOS 平台的默认行为,Android 平台由于其弹出的键盘右上角默认带有关闭键盘的按钮,所以点击空白处不会隐藏键盘。
对于单个页面来说,通过为 TextField 添加 focusNode,点击空白处时使 TextField 失去焦点,实现如下:
class DismissKeyboardDemo extends StatelessWidget {
final FocusNode focusNode = FocusNode();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: GestureDetector(
onTap: () {
focusNode.unfocus();
},
child: Container(
color: Colors.transparent,
alignment: Alignment.center,
child: TextField(
focusNode: focusNode,
),
),
),
);
}
}
当 App 中有多个页面多个 TextField 时,此方式会增加大量重复的代码,因此全局添加点击空白处的监听:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
builder: (context, child) => Scaffold(
body: GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus.unfocus();
}
},
child: child,
),
),
home: DismissKeyboardDemo(),
);
}
}
也可以使用如下方式隐藏键盘:
SystemChannels.textInput.invokeMethod('TextInput.hide');
修改 DismissKeyboardDemo 页面:
class DismissKeyboardDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: TextField(),
),
);
}
}
效果和上面是一样的,同样可以实现点击空白处隐藏键盘。
交流
老孟Flutter博客地址(330个控件用法):http://laomengit.com
欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】: