Flutter 点击空白处关闭软键盘,点击非TextField 关闭软键盘的方法
在Flutter中,可以使用RawGestureDetector
来监听空白处的点击事件,并通过SystemChannels.textInput.invokeMethod('hide')
来隐藏软键盘。以下是实现点击空白处关闭软键盘的示例代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: DismissKeyboard(
child: Center(
child: TextField(),
),
),
),
),
);
}
}
class DismissKeyboard extends StatefulWidget {
final Widget child;
DismissKeyboard({required this.child});
@override
_DismissKeyboardState createState() => _DismissKeyboardState();
}
class _DismissKeyboardState extends State<DismissKeyboard> {
final FocusNode focusNode = FocusNode();
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
focusNode.unfocus();
SystemChannels.textInput.invokeMethod('hide');
},
child: FocusScope.of(context).focusedChild != null
? RawGestureDetector(
gestures: {
TapGestureRecognizer: TapGestureRecognizer()..onTap = () => hideKeyboard(),
},
behavior: HitTestBehavior.opaque,
child: widget.child,
)
: widget.child,
);
}
void hideKeyboard() {
focusNode.unfocus();
SystemChannels.textInput.invokeMethod('hide');
}
@override
void dispose() {
focusNode.dispose();
super.dispose();
}
}
在这个示例中,我们创建了一个DismissKeyboard
组件,它包装了需要使用的其他部分的UI。在DismissKeyboard
的状态中,我们使用GestureDetector
来监听点击事件,并且当点击发生时,如果当前焦点不是在TextField
上,就会触发hideKeyboard
方法,该方法会取消焦点并隐藏软键盘。
评论已关闭