在flutter 如何隐藏软键盘

Flutter提供了多种方法来隐藏软键盘。

以下是一些方法:

  1. 使用 FocusScope.of(context).unfocus() 方法来隐藏软键盘。
FocusScope.of(context).unfocus();

  1. 使用 SystemChannels.textInput.invokeMethod(‘TextInput.hide’) 方法来隐藏软键盘。
import 'package:flutter/services.dart';

SystemChannels.textInput.invokeMethod('TextInput.hide');
  1. 在文本框外部的任何部分点击时,调用 unfocus() 方法来隐藏软键盘。
GestureDetector(
  onTap: () {
    
    
    FocusScope.of(context).unfocus();
  },
  child: Container(
    // Widget tree here
  ),
);
  1. Scaffoldbody中使用 GestureDetector 来包装 ListView 或 SingleChildScrollView,当用户点击屏幕时,隐藏软键盘。
Scaffold(
  body: GestureDetector(
    onTap: () {
    
    
      FocusScope.of(context).unfocus();
    },
    child: SingleChildScrollView(
      child: // Widget tree here,
    ),
  ),
);
  1. 使用 FocusNodeTextField
    TextField 中设置 focusNode 属性,然后在需要隐藏软键盘的地方,调用 focusNode.unfocus() 方法。示例如下:
FocusNode _focusNode = FocusNode();

TextField(
  focusNode: _focusNode,
  // other properties
);

// To hide keyboard
_focusNode.unfocus();

  1. 使用 Navigator.pop(context) 方法来隐藏软键盘
    这个方法通常用于隐藏键盘并返回到上一个屏幕,例如,从一个表单屏幕返回到主屏幕时,隐藏软键盘并返回到主屏幕。示例如下:
Navigator.pop(context);
  1. TextField 中使用 onEditingComplete 属性来隐藏软键盘。
    当用户点击键盘上的“完成”按钮时,这个回调函数将被调用,你可以在这个函数中隐藏软键盘。
TextField(
  onEditingComplete: () {
    
    
    FocusScope.of(context).unfocus();
  },
  // other properties
);

  1. 使用 MediaQuery.of(context).viewInsets.bottom = 0 方法来隐藏软键盘。
    这个方法可以设置底部间距为0,从而将软键盘隐藏。
MediaQuery.of(context).viewInsets.bottom = 0;
  1. 使用 Overlay.of(context).insert(OverlayEntry(builder: (_) => SizedBox.shrink())) 方法来隐藏软键盘,
    这个方法可以向页面中插入一个透明的 SizedBox 来隐藏软键盘。代码如下:
 Overlay.of(context).insert(OverlayEntry(builder: (_) => SizedBox.shrink()));
  1. 使用 SystemChrome.setEnabledSystemUIOverlays([]) 方法来隐藏软键盘
    这个方法可以隐藏屏幕底部的导航栏和状态栏,并在需要时再次显示它们
import 'package:flutter/services.dart';

// To hide system UI
SystemChrome.setEnabledSystemUIOverlays([]);

// To show system UI
SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);

以上就是一些隐藏软键盘的方法。你可以根据你的需求选择其中一种方法来实现。

猜你喜欢

转载自blog.csdn.net/aikongmeng/article/details/129297781