全文转载自: https://cloud.tencent.com/developer/article/1696651

    老孟导读:为什么要实现点击空白处隐藏键盘?因为这是 iOS 平台的默认行为,Android 平台由于其弹出的键盘右上角默认带有关闭键盘的按钮,所以点击空白处不会隐藏键盘。

    对于单个页面来说,通过为 TextField 添加 focusNode,点击空白处时使 TextField 失去焦点,实现如下:

    1. class DismissKeyboardDemo extends StatelessWidget {
    2. final FocusNode focusNode = FocusNode();
    3. @override
    4. Widget build(BuildContext context) {
    5. return Scaffold(
    6. appBar: AppBar(),
    7. body: GestureDetector(
    8. onTap: () {
    9. focusNode.unfocus();
    10. },
    11. child: Container(
    12. color: Colors.transparent,
    13. alignment: Alignment.center,
    14. child: TextField(
    15. focusNode: focusNode,
    16. ),
    17. ),
    18. ),
    19. );
    20. }
    21. }

    image.png

    当 App 中有多个页面多个 TextField 时,此方式会增加大量重复的代码,因此全局添加点击空白处的监听:

    1. class MyApp extends StatelessWidget {
    2. @override
    3. Widget build(BuildContext context) {
    4. return MaterialApp(
    5. title: 'Flutter Demo',
    6. builder: (context, child) => Scaffold(
    7. body: GestureDetector(
    8. onTap: () {
    9. FocusScopeNode currentFocus = FocusScope.of(context);
    10. if (!currentFocus.hasPrimaryFocus &&
    11. currentFocus.focusedChild != null) {
    12. FocusManager.instance.primaryFocus.unfocus();
    13. }
    14. },
    15. child: child,
    16. ),
    17. ),
    18. home: DismissKeyboardDemo(),
    19. );
    20. }
    21. }

    也可以使用如下方式隐藏键盘:

    1. SystemChannels.textInput.invokeMethod('TextInput.hide');

    修改 DismissKeyboardDemo 页面:

    1. class DismissKeyboardDemo extends StatelessWidget {
    2. @override
    3. Widget build(BuildContext context) {
    4. return Scaffold(
    5. appBar: AppBar(),
    6. body: Center(
    7. child: TextField(),
    8. ),
    9. );
    10. }
    11. }

    效果和上面是一样的,同样可以实现点击空白处隐藏键盘。
    image.png