老孟导读:为什么要实现点击空白处隐藏键盘?因为这是 iOS 平台的默认行为,Android 平台由于其弹出的键盘右上角默认带有关闭键盘的按钮,所以点击空白处不会隐藏键盘。 对于单个页面来说,通过为 T
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,),);
}
}
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');
class DismissKeyboardDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),body: Center(
child: TextField(),);
}
}