为什么要实现点击空白处隐藏键盘?因为这是 iOS 平台的默认行为,Android 平台由于其弹出的键盘右上角默认带有关闭键盘的按钮,所以点击空白处不会隐藏键盘。
单个页面,可以这样做:
class DismissKeyboardPage 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,
),
),
),
);
}
}
该方法的缺点是每个 TextField 节点都得挂载 focusNode。而不指定的话,会有默认的 focusNode,可以通过下面的方法获取。
全局设置点击空白处隐藏键盘:
class App extends StatelessWidget {
App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'DismissKeyboard Example',
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: DismissKeyboardPage(),
);
}
}
标签:focusNode,键盘,点击,context,child,flutter,空白处
From: https://www.cnblogs.com/lemos/p/16609933.html