英文:
How to remove validation warning in Text Form Field in Flutter?
问题
我在Flutter的表单中有两个文本表单字段,已经添加了验证器以提供无效值的警告。但是我希望当用户重新开始输入时,警告会隐藏。
我以为可以使用onTap或onChanged函数来实现这一点,但是找不到方法来做到这一点。
英文:
I have two Text Form Fields inside a Form in flutter. I have added validator to give warnings for invalid value. But I want the warnings to hide when the user starts typing again.
I thought I could achieve this using onTap or onChanged function, but couldn't figure out a way to do this.
答案1
得分: 1
TextFormField
有一个focusNode
属性。当用户编辑一个TextFormField
时,与该字段关联的FocusNode
将具有输入焦点。您可以通过节点的hasFocus
属性来查询FocusNode
的状态。
因此,为每个TextFormField
创建并传递一个FocusNode
,然后在您的验证函数中查询相关节点的状态。
例如,电子邮件TextFormField
的代码应如下所示:
final emailNode = FocusNode();
...
TextFormField(
focusNode: emailNode,
validator: (value) {
...
else if (widget.inputType == InputType.email &&
!Validation.isValidEmail(value) &&
!emailNode.hasFocus){
return '请输入有效的电子邮件地址!';
}
},
),
这样,当用户点击电子邮件字段并开始输入新值时,电子邮件字段将具有焦点,因此验证器中的最后一个条件将为false
,因此错误消息将消失。当用户点击密码字段时,电子邮件字段将失去焦点,因此!emailNode.hasFocus
将为真,并且电子邮件字段下的错误消息将重新出现,如果电子邮件字段中的值不是有效的电子邮件地址。
P.S. 下次请发布代码而不是截图。
英文:
TextFormField
s have a focusNode
property. While the user is editing a TextFormField
the FocusNode
associated with that field will have input focus. You can query the state of a FocusNode
through the hasFocus
property of the node.
So create and pass a FocusNode
for each TextFormField
, and then query the state of the relevant node in your validator function.
For example the code for the email TextFormField
should look like this:
final emailNode = FocusNode();
...
TextFormField(
focusNode: emailNode,
validator: (value) {
...
else if(widget.inputType == InputType.email &&
!Validation.isValidEmail(value) &&
!emailNode.hasFocus){
return 'Please enter a valid email!;
}
},
),
This way when the user taps the email field and starts entering a new value the email field will have focus, so the last condition in the validator will be false
, so the error message will disappear. When the user taps the password field the email field will lose focus, so the !emailNode.hasFocus
will be true, and the error message under the email field will reappear, if the value in the email field is not a valid email address.
P.S. Next time post code instead of a screenshot please.
答案2
得分: 0
autovalidateMode:AutovalidateMode.onUserInteraction,
英文:
try making autoValidationMode of your widgets onUserInteraction:
autovalidateMode:AutovalidateMode.onUserInteraction,
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论