Flutter实现点击空白区域隐藏软键盘

3,512 阅读1分钟

实现思路: 使用GestureDetector将最外层的MaterialApp包裹起来,监听onTap点击事件,使用FocusSocpe相关的api来控制软件的显示和隐藏。当键盘显示的时候,将键盘隐藏。

封装Widget

/// 因为不需要保持状态,所以这里继承的是StatelessWidget
class HideKeyboard extends StatelessWidget {
  final Widget child;

  const HideKeyboard({Key key, this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: child,
      onTap: () {
        FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus &&
            currentFocus.focusedChild != null) {
          /// 取消焦点,相当于关闭键盘
          FocusManager.instance.primaryFocus.unfocus();
        }
      },
    );
  }
}

使用

main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    /// 放在app最外层即可。
    return HideKeyboard(
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text("Hide soft keyboard demo"),
          ),
          body: Container(
            child: Text("hello,world"),
          ),
        ),
      ),
    );
  }
}