Lao Meng's Guide: Why do you want to hide the keyboard by clicking the blank space ? Because this is the default behavior of the iOS platform, the Android platform has a button to close the keyboard by default in the upper right corner of the pop-up keyboard, so clicking the blank space will not hide the keyboard.
For a single page, by adding focusNode to the TextField, the TextField loses the focus when clicking on the blank space, the implementation is as follows:
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,
),
),
),
);
}
}
When there are multiple TextFields on multiple pages in the App, this method will increase a lot of repetitive code, so globally add a listener that clicks on the blank space:
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(),
);
}
}
You can also hide the keyboard as follows:
SystemChannels.textInput.invokeMethod('TextInput.hide');
Modify the DismissKeyboardDemo page:
class DismissKeyboardDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: TextField(),
),
);
}
}
The effect is the same as above, and the keyboard can also be hidden by clicking the blank space.
communicate with
Laomeng Flutter blog address (330 control usage): http://laomengit.com
Welcome to join the Flutter exchange group (WeChat: laomengit) and follow the public account [Lao Meng Flutter]: