【问题标题】:Flutter form button enabled not updating after fields validation字段验证后启用 Flutter 表单按钮不更新
【发布时间】:2020-07-20 01:45:56
【问题描述】:


我仍在学习 Flutter 并为此摸不着头脑。
我有一个包含 3 个字段(电子邮件、密码和密码确认)的表单。 我正在使用验证器并更新用作按钮启用状态条件的变量。
问题是当我更改例如电子邮件时,按钮启用状态没有更新...
如果我热重启,它将更新按钮状态..
如何强制按钮重新评估其状态?
这样做的 Flutter 方法是什么?
谢谢

  bool _validEmail = false;
  bool _validPassword = false;
  bool _validPasswordConfirmation = false;
  bool _validAccount = false;
  SignUpError _serverSignUpErrors = null;


Form signup_form() {
return Form(
    key: _formKey,
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        //Email field
        Container(
          margin: EdgeInsets.symmetric(vertical: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                "Email",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
              ),
              SizedBox(
                height: 10,
              ),
              TextFormField(
                  controller: _emailFieldController,
                  obscureText: false,
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      fillColor: Color(0xfff3f3f4),
                      filled: true),
                  onChanged: (String value) {
                    if(_serverSignUpErrors?.email_errors?.isNotEmpty == true)
                      _serverSignUpErrors.email_errors.clear();
                  },
                  autovalidate: true,
                  validator: (value) {
                    _validEmail = false;
                    if (value.isEmpty)
                      return 'Please enter some text';
                    //Validate email
                    String p = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
                    RegExp regExp = new RegExp(p);
                    if(!regExp.hasMatch(value))
                      return 'Invalid email';
                    if(_serverSignUpErrors?.email_errors?.isNotEmpty == true)
                      return _serverSignUpErrors.email_errors.join(';');
                    _validEmail = true;
                    return null;
                  }
              )
            ],
          ),
        ),

        //Password field
        Container(
          margin: EdgeInsets.symmetric(vertical: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                "Password",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
              ),
              SizedBox(
                height: 10,
              ),
              TextFormField(
                  controller: _passwordController,
                  obscureText: true,
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      fillColor: Color(0xfff3f3f4),
                      filled: true),
                  onChanged: (String value) {
                    if(_serverSignUpErrors?.password_errors?.isNotEmpty == true)
                      _serverSignUpErrors.password_errors.clear();
                    this.didChangeDependencies();
                  },
                  autovalidate: true,
                  validator: (value) {
                    _validPassword = false;
                    if (value.isEmpty || value.length < 4)
                      return 'Password must be at least 6 chars wide';
                    if(_serverSignUpErrors?.password_errors?.isNotEmpty == true)
                      return _serverSignUpErrors.password_errors.join(';');
                      _validPassword = true;
                    return null;
                  }
              )
            ],
          ),
        ),

        //Password field
        Container(
          margin: EdgeInsets.symmetric(vertical: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                "Password confirmation",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
              ),
              SizedBox(
                height: 10,
              ),
              TextFormField(
                  controller: _passwordConfirmationController,
                  obscureText: true,
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      fillColor: Color(0xfff3f3f4),
                      filled: true),
                  onChanged: (String value) {
                    if(_serverSignUpErrors?.password_confirmation_errors?.isNotEmpty == true)
                      _serverSignUpErrors.password_confirmation_errors.clear();
                    this.didChangeDependencies();
                  },
                  autovalidate: true,
                  validator: (value) {
                    _validPasswordConfirmation = false;
                    if (value.isEmpty)
                      return 'Please enter password confirmation';
                    if(value != _passwordController.text)
                      return 'Password confirmation doesn\'t match password';
                    if(_serverSignUpErrors?.password_confirmation_errors?.isNotEmpty == true)
                      return _serverSignUpErrors.password_confirmation_errors.join(';');
                    _validPasswordConfirmation = true;
                    return null;
                  }
              )
            ],
          ),
        ),
        Center(
          child: FlatButton(
              onPressed: (_validEmail && _validPassword && _validPasswordConfirmation && _validAccount == false) ? () async => await onRegister() : null,
              disabledColor: Colors.blueGrey,
              child: Text(
                'Register Now',
                style: TextStyle(fontSize: 20, color: Colors.white),
              ),
              color: Colors.blue, //specify background color for the button here
              colorBrightness: Brightness.dark, //specify the color brightness here, either `Brightness.dark` for darl and `Brightness.light` for light
              highlightColor: Colors.red, //color when the button is being actively pressed, quickly fills the button and fades out after
              padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 5.0), // gives padding to the button
            ),
        ),
      ]
    )
  );

}

【问题讨论】:

    标签: forms validation flutter submit


    【解决方案1】:

    看来您== false 正在扭转您的预期行为。不确定这是否是您想要的。

    onPressed: (_validEmail && _validPassword && _validPasswordConfirmation && _validAccount == false) ? () async => await onRegister() : null,
    

    要解决您的错误,您应该使用_validEmail_validPassword 等变量将更改状态的任何内容用setState(() {}); 包装起来。这将在您更改状态时重建小部件(包括按钮),以便在您需要时启用它并且您将获得所需的行为。

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 2021-05-23
      • 2011-11-29
      • 1970-01-01
      相关资源
      最近更新 更多