Flutter 如何将焦点添加到存在验证错误的textformfield
我的表单中有textformfields。当我点击提交按钮时,验证错误显示在textformfield下。我想将焦点添加到该特定字段,这样当用户单击“保存”按钮时,该字段就会弹出。用户不需要向上滚动并键入信息。用户应该能够直接开始键入。在当前场景中,用户感到困惑,不知道为什么保存按钮不起作用。Bcoz在向上滚动之前,错误未知Flutter 如何将焦点添加到存在验证错误的textformfield,flutter,validation,setfocus,Flutter,Validation,Setfocus,我的表单中有textformfields。当我点击提交按钮时,验证错误显示在textformfield下。我想将焦点添加到该特定字段,这样当用户单击“保存”按钮时,该字段就会弹出。用户不需要向上滚动并键入信息。用户应该能够直接开始键入。在当前场景中,用户感到困惑,不知道为什么保存按钮不起作用。Bcoz在向上滚动之前,错误未知 TextFormField( controller: NoteController, valid
TextFormField(
controller: NoteController,
validator: (String value){
if(value.isEmpty)
{
return "Note can't be null";
}
else
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: const BorderSide(width: 2.0),)),
keyboardType: TextInputType.multiline,
minLines: 5,
maxLines: 5,
onChanged: (value) {
this.note.note = value;
},
),
bool validateAndSave() {
final form = globalFormKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
void _save() async {
if (validateAndSave()) {
}
}
您可以使用FocusNode和TextField实现这一点。你可以在这里了解更多 让我给你看一个例子(试过了,效果很好): 在生成方法之前:
final FocusNode noteFocus = FocusNode();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
// Add FocusNode to TextFieldForm
focusNode: noteFocus,
validator: (value) {
if (value == null || value.isEmpty) {
// Request focus in case of error
noteFocus.requestFocus();
return "Note can't be null";
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Validated');
}
},
child: Text('Submit'),
)
],
),
),
在构建方法中:
final FocusNode noteFocus = FocusNode();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
// Add FocusNode to TextFieldForm
focusNode: noteFocus,
validator: (value) {
if (value == null || value.isEmpty) {
// Request focus in case of error
noteFocus.requestFocus();
return "Note can't be null";
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Validated');
}
},
child: Text('Submit'),
)
],
),
),
如果您还需要什么,请告诉我:)像这样使用FocusNode
FocusNode focusNode = FocusNode();
TextFormField(
controller: NoteController,
focusNode: focusNode,
validator: (String value){
if(value.isEmpty)
{
Focus.of(context).requestFocus(focusNode);
return "Note can't be null";
}
else
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: const BorderSide(width: 2.0),)),
keyboardType: TextInputType.multiline,
minLines: 5,
maxLines: 5,
onChanged: (value) {
this.note.note = value;
},
),
它不起作用。焦点没有转移到具有errorFocus.of()的textformfield,该字段使用的上下文在给定上下文和最近的FocusScope小部件之间不包含焦点。此外,验证错误也没有显示出来,但使用这个如何为显示错误的字段设置焦点我添加了一个示例来向您展示:)@FathimaShafanaNo它不工作。文本字段未接收焦点。