【问题标题】:Flutter: Validate only one TextFormFieldFlutter:仅验证一个 TextFormField
【发布时间】:2020-10-01 19:34:49
【问题描述】:

我正在使用 Flutter 构建用户注册表单。我需要实现以下目标:-

  1. 要求用户输入他们喜欢的用户 ID

  2. TextFormField 末尾添加一个按钮,以便用户验证该 User ID 是否已被占用。

  3. 单击该按钮时,它将调用验证器函数以仅验证 用户 ID(而不是表单中的任何其他字段)

  4. 无论用户是否点击验证按钮,提交表单时用户ID仍然会被验证。

我尝试了很多方法,似乎唯一的解决方案是将用户 ID 与所有其他表单拆分为一个单独的表单。

请问有没有比这更好的解决方案?

【问题讨论】:

  • 调用FormFieldState.validate()方法(或使用isValid属性)
  • @pskink,我几乎让它工作了。除了错误消息没有正确显示。你能帮忙吗?
  • @pksink,谢谢我现在可以使用了。好像我原来的设计太复杂了。将编辑我的帖子。

标签: flutter


【解决方案1】:
  1. 创建GlobalKey
var _formKey = GlobalKey<FormState>();    
  1. _formKey 添加到您的TextFormField,表单小部件应仅添加到您要验证的字段。
Padding(
  padding: EdgeInsets.only(left: 30.0, right: 30.0, bottom: 10.0),
  child: Form(
    key: _formKey,
    child: TextFormField(
      maxLines: 1,
      style: TextStyle(decoration: TextDecoration.none, color: Colors.grey[900], fontSize: 14.0, fontFamily: 'Montserrat', fontWeight: FontWeight.w500, letterSpacing: 0.0,),
      decoration: InputDecoration(labelText: 'Type here...', alignLabelWithHint: true, border: OutlineInputBorder(borderRadius: BorderRadius.circular(5.0),)),
      validator: (_post) => _post.toString().trim().length == 0 ? "Empty text" : null,
      onSaved: (_post) => _postText = _post.toString().trim(),
    ),
  ),
)
  1. 然后任何 Button 的 OnClick 调用 Validate 函数。
void _validateInputs() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
       // Call your Method
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2019-08-12
    • 2020-10-27
    • 2021-08-10
    • 2019-04-11
    • 2021-08-30
    • 2023-01-12
    相关资源
    最近更新 更多