FocusNode 主要提供焦点控制功能
1. FocusNode
1.1 收起或者隐藏键盘
class MSFocusNodeDemo1 extends StatelessWidget {
MSFocusNodeDemo1({Key? key}) : super(key: key);
final _normalNode = FocusNode();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("FocusNodeDemo")),
body: TextField(
focusNode: _normalNode,
onSubmitted: (string) {
print(string);
// _normalNode.unfocus();
FocusManager.instance.primaryFocus!.unfocus();
},
),
);
}
}
以下两种方式均可隐藏键盘。
normalNode.unfocus();
FocusManager.instance.primaryFocus.unfocus(); // 拿到对应的 FocusNode
1.2 自动跳转焦点
使用 FocusScope 控件,以及 FocusScopeNode 来对焦点进行管理
class MSFocusNodeDemo2 extends StatelessWidget {
MSFocusNodeDemo2({Key? key}) : super(key: key);
final FocusScopeNode _scopeNode = FocusScopeNode();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("FocusNodeDemo2")),
body: FocusScope(
node: _scopeNode,
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 16),
children: [
_textField(),
_textField(),
_textField(),
_textField(),
_textField(),
_textField(),
_textField(),
_textField(),
],
),
),
);
}
TextField _textField() {
return TextField(
decoration: InputDecoration(hintText: "请输入文本"),
onEditingComplete: () {
// 跳到下一个textFiled
_scopeNode.nextFocus();
},
);
}
}
至此,我们已经实现了光标自动下跳的功能了
103.gif1.3 跳过部分控件的 FocusNode
在 flutter 中很多子控件其实也有 focusNode 属性,与 TextField 一样。
在这里 FocusScopeNode 就一视同仁了,认为他也是可以聚焦的一份子,所以有时候会卡在某一个不是 TextField 的控件上。
设置 skipTraversal 属性,FocusScopeNode 会自动跳过设置为 true 的控件
class MSFocusNodeDemo3 extends StatelessWidget {
MSFocusNodeDemo3({Key? key}) : super(key: key);
final FocusScopeNode _scopeNode = FocusScopeNode();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("FocusNodeDemo3")),
body: FocusScope(
node: _scopeNode,
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 16),
children: [
_textField(),
_textField(),
_btnField(),
_textField(),
_textField(),
_btnField(),
_textField(),
_textField(),
],
),
),
);
}
TextField _textField() {
return TextField(
decoration: InputDecoration(hintText: "请输入文本"),
onEditingComplete: () {
_scopeNode.nextFocus();
},
);
}
Widget _btnField() {
return Row(
children: [
Expanded(child: _textField()),
ElevatedButton(
onPressed: () {},
child: Text("点击"),
focusNode: FocusNode(skipTraversal: true),
)
],
);
}
}
102.gif
网友评论