如何在Flutter中移除文本表单字段中的验证警告?

huangapple go评论88阅读模式
英文:

How to remove validation warning in Text Form Field in Flutter?

问题

我在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.

How to hide these warnings?如何在Flutter中移除文本表单字段中的验证警告?

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. 下次请发布代码而不是截图。

英文:

TextFormFields 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,

huangapple
  • 本文由 发表于 2023年7月23日 17:17:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定