#flutter #flutter-test
Вопрос:
Поэтому я хочу создавать сообщения об ошибках на странице входа, но сообщения не появляются или не очень хорошо работают как с сообщениями об ошибках электронной почты, так и с сообщениями об ошибках пароля. Всякий раз, когда я нажимал на кнопку «ВОЙТИ», я заставлял ее всегда переходить на следующую страницу, а этого не должно было быть. Вот мой код:
ФОРМА ДЛЯ ВХОДА В СИСТЕМУ
class sign_in_form extends StatefulWidget { const sign_in_form({Key? key}) : super(key: key); @override _sign_in_formState createState() =gt; _sign_in_formState(); } class _sign_in_formState extends Statelt;sign_in_formgt; { final _formKey = GlobalKeylt;FormStategt;(); String? email; String? password; final Listlt;String?gt; 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: lt;Widgetgt;[ 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) =gt; 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) =gt; password = newValue, onChanged: (value){ if (value.isNotEmpty) { removeError(error: "Please Enter your password"); } else if (value.length gt;= 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 Listlt;String?gt; errors; @override Widget build(BuildContext context) { return Column( children: List.generate( errors.length, (index) =gt; 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), ], ); } }
Ответ №1:
Please refer to below example code of error messages handling
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 = GlobalKeylt;FormStategt;(); int validateEmail(String emailAddress) { String patttern = r"^[a-zA-Z0-9.!#$%amp;'* /=?^_`{|}~-] @[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 amp;amp; pswd.isNotEmpty amp;amp; pswd.length lt;= 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"ss")), 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"ss")), 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 lt;= 8) { pswdFocus.requestFocus(); } }, child: Text("Validate"), ) ], ), ), ); } }