Кнопка формы флаттера не обновляется после проверки полей - PullRequest
0 голосов
/ 07 апреля 2020

Я все еще изучаю Флаттер и ломаю голову вокруг этого. У меня есть форма с 3 полями (адрес электронной почты, пароль и подтверждение пароля). Я использую валидаторы и обновляю переменную, которая используется как условие для состояния включения кнопки. Проблема в том, что состояние включенной кнопки не обновляется, когда я изменяю, например, адрес электронной почты ... Если я перезагружу, он обновит состояние кнопки .. Как заставить кнопку переоценить ее состояние? Как Флаттер это делает? Спасибо

  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
            ),
        ),
      ]
    )
  );

}

1 Ответ

1 голос
/ 08 апреля 2020

Кажется, вы == false изменили свое намеченное поведение. Не уверен, что это именно то, что вам нужно.

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

Чтобы устранить ошибку, вы должны обернуть все, где вы меняете состояние, переменными, такими как _validEmail, _validPassword, et c. с setState(() {});. Это перестроит виджет, включая кнопку, когда вы измените состояние, чтобы он включился, когда вы захотите, и вы получите желаемое поведение.

...