问题描述
我是 Flutter 的新手.
I am new to Flutter.
我正在使用以下小部件构建具有多个文本输入的表单:Form、TextFormField.出现的键盘不显示下一个"(应该将焦点转移到下一个字段)字段操作,而是完成"操作(隐藏键盘).
I am building a form with multiple text inputs using following widgets: Form, TextFormField. The keyboard that appears doesn't show "next" (which should shift the focus to next field) field action instead it is "done" action (which hides the keyborad).
我在官方文档中寻找任何提示,没有直接找到可以做的事情.我虽然登陆了 FocusNode(cookbook, api 文档).它提供了通过某个按钮或应用程序上的任何其他操作来转移焦点的机制,但我希望它位于 keyboard 中.
I looked for any hints in official docs, found nothing directly that can be done.I although landed on FocusNode(cookbook, api doc). It provides with mechanism to shift focus by some button or any other action on app, but I want it to be in keyboard.
推荐答案
找到了实现它的方法.
显示下一个图标而不是完成 - 将
textInputAction
参数设置为TextInputAction.next
使用onFieldSubmitted
回调请求下一个字段的焦点节点.
Using onFieldSubmitted
callback to request focus node of next field.
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() 方法中初始化 FocusNode,并在父 Widget 的 dispose() 中进行 dispose.- @AntonDerevyanko
As stated in the documentation (flutter.io/docs/cookbook/forms/focus), - we also need to manage FocusNode lifecycle. So, init FocusNode in the init() method and dispose in dispose() of the parent Widget. - @AntonDerevyanko
更新:同样可以不使用FocusNode
和FocusScopeNode
,只需调用FocusScope.of(context).nextFocus()
,看看 CopsOnRoad 解决方案 如何做到这一点.更多信息请查看 doc.
Update: The same can be achieved without FocusNode
and FocusScopeNode
, by simply calling FocusScope.of(context).nextFocus()
, take a look at CopsOnRoad solution on how to do that. For more info check doc.
这篇关于如何将焦点转移到 Flutter 中的下一个 TextField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!