如何在flutter中将焦点转移到下一个文本字段?
问题内容:
我是Flutter的新手。
我正在使用以下窗口小部件构建具有多个文本输入的表单:Form,TextFormField。出现的键盘不显示“下一个”(应将焦点转移到下一个字段)字段操作,而是“完成”操作(隐藏键盘)。
我在官方文档中寻找任何提示,没有发现直接可以做的事情。我虽然登陆了FocusNode(cookbook,api
doc
)。它提供了一种机制,可以通过应用程序上的某些按钮或其他任何操作来转移焦点,但是我希望它位于 键盘中 。
问题答案:
找到了一种方法来实现它。
-
显示下一个图标而不是完成-将
textInputAction
参数设置为TextInputAction.next
-
使用
onFieldSubmitted
回调请求下一个字段的焦点节点。
class FormWidget extends StatelessWidget{
final focus = FocusNode();
@override
Widget build(BuildContext context) {
return Form(
child: SingleChildScrollView(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextFormField(
textInputAction: TextInputAction.next,
autofocus: true,
decoration: InputDecoration(labelText: "Input 1"),
onFieldSubmitted: (v){
FocusScope.of(context).requestFocus(focus);
},
),
TextFormField(
focusNode: focus,
decoration: InputDecoration(labelText: "Input 2"),
),
],
),
),
);
}
}
编辑:如文档所述(flutter.io/docs/cookbook/forms/focus),-我们还需要管理FocusNode生命周期。因此,请使用init()方法中的initFocusNode并将其放置在父Widget的dispose()中。-@AntonDerevyanko
更新:如果没有FocusNode
和FocusScopeNode
,只需调用FocusScope.of(context).nextFocus()
,看看CopsOnRoad解决方案的实现方法,就可以实现相同的目的。有关更多信息,请检查doc。