参考:https://blog.csdn.net/weixin_27013291/article/details/112715846
1.创建FocusNode
//创建FocusNode对象实例 FocusNode focusNode = FocusNode();
2.初始化函数中添加焦点监听
@override
void initState(){
super.initState();
//输入框焦点监测
_focusNode.addListener((){
if (!_focusNode.hasFocus) {
print('失去焦点');
}else{
print('得到焦点');
}
});
}
3.在TextField中引用FocusNode
new TextField( //引用FocusNode focusNode: focusNode, ),
4.在页面Widget销毁时,释放focusNode
//页面销毁 @override void dispose() { super.dispose(); //释放 focusNode.dispose(); }
一般情况需要点击空白处失去焦点,写在当前页面的最顶处组件
GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { // 触摸收起键盘 FocusScope.of(context).requestFocus(FocusNode()); }, child: Container() )
常用方法
//获取焦点 void getFocusFunction(BuildContext context){ FocusScope.of(context).requestFocus(focusNode); } //失去焦点 void unFocusFunction(){ focusNode.unfocus(); } //隐藏键盘而不丢失文本字段焦点: void hideKeyBoard(){ SystemChannels.textInput.invokeMethod('TextInput.hide'); }