【问题标题】:validation error messages is not working properly flutter验证错误消息无法正常工作
【发布时间】:2023-04-06 02:16:01
【问题描述】:

所以我想在登录页面上制作错误消息,但是这些消息没有弹出或者在电子邮件和密码错误消息上都不能很好地工作。每当我点击“登录”按钮时,我总是会转到下一页,但它不应该这样做。这是我的代码:

登录表格

class sign_in_form extends StatefulWidget {
  const sign_in_form({Key? key}) : super(key: key);

  @override
  _sign_in_formState createState() => _sign_in_formState();
}

class _sign_in_formState extends State<sign_in_form> {
  final _formKey = GlobalKey<FormState>();
  String? email;
  String? password;

  final List<String?> errors = [];

  void addError ({String? error}) {
    if (!errors.contains(error)) {
      setState(() {
        errors.add(error);
      });
    }
  }

  void removeError ({String? error}) {
    if (!errors.contains(error)) {
      setState(() {
        errors.remove(error);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          buildEmailFormField(),
          SizedBox(height: getProportionateScreenHeight(20)),
          buildPasswordFormField(),
          SizedBox(height: getProportionateScreenHeight(20)),
          errors_form(errors: errors),
          SizedBox(height: getProportionateScreenHeight(20)),
          splash_button(
            press: () {
              if (_formKey.currentState!.validate()) {
                _formKey.currentState!.save();
              }
            },
          ),
        ],
      ),
    );
  }
  TextFormField buildEmailFormField() {
    return TextFormField(
      keyboardType: TextInputType.emailAddress,
      onSaved: (newValue) => email = newValue,
      onChanged: (value) {
        if (value.isNotEmpty) {
          removeError(error: "Please Enter your email");
        }
        else if (emailValidatorRegExp.hasMatch(value)) {
          removeError(error: "Please Enter Valid Email");
        }
        return;
      },
      validator: (value) {
        if (value!.isEmpty) {
          addError(error: "Please Enter your email");
          return "";
        }
        else if (!emailValidatorRegExp.hasMatch(value)) {
          addError(error: "Please Enter Valid Email");
          return "";
        }
        return value;
      },
      decoration: const InputDecoration(
        labelText: "Email",
        hintText: "Enter your email",
        floatingLabelBehavior: FloatingLabelBehavior.always,
        suffixIcon: Padding(
          padding: EdgeInsets.fromLTRB(0, 20, 20, 20),
          child: Icon(Icons.email),
        ),
      ),
    );
  }
  TextFormField buildPasswordFormField() {
    return TextFormField(
      obscureText: true,
      onSaved: (newValue) => password = newValue,
      onChanged: (value){
        if (value.isNotEmpty) {
          removeError(error: "Please Enter your password");
        }
        else if (value.length >= 8) {
          removeError(error: "Password is too short");
        }
        return;
      },
      validator: (value){
        if (value!.isEmpty) {
          addError(error: "Please Enter your password");
          return "";
        }
        else if (!emailValidatorRegExp.hasMatch(value)) {
          addError(error: "Password is too short");
          return "";
        }
        return null;
      },
      decoration: const InputDecoration(
        labelText: "Password",
        hintText: "Enter your password",
        floatingLabelBehavior: FloatingLabelBehavior.always,
        suffixIcon: Padding(
          padding: EdgeInsets.fromLTRB(0, 20, 20, 20),
          child: Icon(Icons.lock),
        ),
      ),
    );
  }
}
  

我的错误表格

class errors_form extends StatelessWidget {
  const errors_form({Key? key, required this.errors,}) : super(key: key);
  final List<String?> errors;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: List.generate(
          errors.length, (index) => form_error_text(errors: errors[index]!)),
    );
  }
  Row form_error_text ({required String errors}) {
    return Row(
      children: [
        SvgPicture.asset(
          "assets/icons/Error.svg",
          height: getProportionateScreenWidth(14),
          width: getProportionateScreenWidth(14),
        ),
        SizedBox(width: getProportionateScreenWidth(14)),
        Text(errors),
      ],
    );
  }
}

【问题讨论】:

    标签: flutter flutter-test


    【解决方案1】:

    请参考下面的错误信息处理示例代码

    class MainScreen extends StatelessWidget {
      MainScreen({Key key}) : super(key: key);
    
      final TextEditingController emailController = TextEditingController();
      final FocusNode emailFocus = FocusNode();
      final TextEditingController pswdController = TextEditingController();
      final FocusNode pswdFocus = FocusNode();
      final _validationKey = GlobalKey<FormState>();
    
      int validateEmail(String emailAddress) {
        String patttern =
            r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]"
            r"{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]"
            r"{0,253}[a-zA-Z0-9])?)*$";
        RegExp regExp = new RegExp(patttern);
        if (emailAddress.isEmpty || emailAddress.length == 0) {
          return 1;
        } else if (!regExp.hasMatch(emailAddress)) {
          return 2;
        } else {
          return 0;
        }
      }
    
      int validatePassword(String pswd) {
        if (pswd.isEmpty || pswd.length == 0) {
          return 1;
        } else if (pswd != null && pswd.isNotEmpty && pswd.length <= 8) {
          return 2;
        } else {
          return 0;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.lightBlue,
            automaticallyImplyLeading: true,
            leading: Icon(
              Icons.arrow_back,
            ),
            title: Text("Example"),
            centerTitle: true,
          ),
          body: Container(
            padding: EdgeInsets.all(15.0),
            child: Column(
              children: [
                Form(
                  key: _validationKey,
                  child: Column(
                    children: [
                      /* Email */
                      TextFormField(
                        autovalidateMode: AutovalidateMode.onUserInteraction,
                        /* autovalidate is disabled */
                        controller: emailController,
                        inputFormatters: [
                          FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                          FilteringTextInputFormatter.deny(RegExp(
                              r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                        ],
                        keyboardType: TextInputType.text,
                        maxLength: 160,
                        onChanged: (val) {},
                        maxLines: 1,
                        validator: (value) {
                          int res = validateEmail(value);
                          if (res == 1) {
                            return "Please enter your email address";
                          } else if (res == 2) {
                            return "Please enter valid email address";
                          } else {
                            return null;
                          }
                        },
                        focusNode: emailFocus,
                        autofocus: false,
                        decoration: InputDecoration(
                          errorMaxLines: 3,
                          counterText: "",
                          filled: true,
                          fillColor: Colors.white,
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                              color: Color(0xffE5E5E5),
                            ),
                          ),
                          disabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                              color: Color(0xffE5E5E5),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                              color: Color(0xffE5E5E5),
                            ),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(Radius.circular(4)),
                              borderSide: BorderSide(
                                width: 1,
                                color: Colors.red,
                              )),
                          focusedErrorBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                              color: Colors.red,
                            ),
                          ),
                          hintText: "Enter your email" ?? "",
                        ),
                      ),
                      SizedBox(
                        height: 15.0,
                      ),
    
                      /* Password */
                      TextFormField(
                        autovalidateMode: AutovalidateMode.onUserInteraction,
                        /* autovalidate is disabled */
                        controller: pswdController,
                        inputFormatters: [
                          FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                          FilteringTextInputFormatter.deny(RegExp(
                              r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                        ],
                        keyboardType: TextInputType.text,
                        maxLength: 160,
                        onChanged: (val) {},
                        obscureText: true,
                        maxLines: 1,
                        validator: (value) {
                          int res = validatePassword(value);
                          if (res == 1) {
                            return "Please enter password";
                          } else if (res == 2) {
                            return "Please enter minimum 9 characters";
                          } else {
                            return null;
                          }
                        },
                        focusNode: pswdFocus,
                        autofocus: false,
                        decoration: InputDecoration(
                          errorMaxLines: 3,
                          counterText: "",
                          filled: true,
                          fillColor: Colors.white,
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                              color: Color(0xffE5E5E5),
                            ),
                          ),
                          disabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                              color: Color(0xffE5E5E5),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                              color: Color(0xffE5E5E5),
                            ),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(Radius.circular(4)),
                              borderSide: BorderSide(
                                width: 1,
                                color: Colors.red,
                              )),
                          focusedErrorBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            borderSide: BorderSide(
                              width: 1,
                              color: Colors.red,
                            ),
                          ),
                          hintText: "Enter password" ?? "",
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 15.0,
                ),
                OutlinedButton(
                  onPressed: () {
                    _validationKey.currentState.validate();
                    if (emailController.text.isEmpty) {
                      emailFocus.requestFocus();
                    } else if (pswdController.text.isEmpty ||
                        pswdController.text.length <= 8) {
                      pswdFocus.requestFocus();
                    }
                  },
                  child: Text("Validate"),
                )
              ],
            ),
          ),
        );
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多