Проверка текстовой формы Flutter не отображается - PullRequest
0 голосов
/ 14 июля 2020

Я просмотрел пару руководств о том, как заставить валидаторы работать, но ни один из них, похоже, не работал. Кто-нибудь может мне с этим помочь? Это код простой страницы входа. Мои валидаторы не отображаются на экране, если они обнаруживают какую-либо ошибку. Я смотрел обучающие программы, где он отображается красным, но в моем приложении он вообще не отображается.

 class UserLogin extends StatefulWidget {

  UserLogin({this.auth,this.onSignedIn});
  final BaseAuth auth;
  final VoidCallback onSignedIn;
  @override
  State<StatefulWidget> createState()=> _UserLoginState();
}

class _UserLoginState extends State<UserLogin> {

  final formkey = GlobalKey<FormState>();

  bool _validateAndSave()
  {
    final form = formkey.currentState;
    if(form.validate())
      {
        form.save();
        return true;
      }
    else
      return false;
  }

   static final incorrect_icon = Icon(
     Icons.error,
     color: Colors.pink,
   );

   void _validateAndSubmit() async
   {

     if(_validateAndSave()) {
       try {
         String userId = await widget.auth.signIn(emailid, password);
         print('Signed in! $userId');
         //widget.onSignedIn();
         Navigator.push(context, MaterialPageRoute(builder: (context)=>Feed()));
       }
       catch (e) {
         print('Error: $e');
       }
     }

   }



   static final TextEditingController emailContr = new TextEditingController();
   static final TextEditingController passwordContr = new TextEditingController();

   static String get emailid => emailContr.text;
   static String get password => passwordContr.text;

   final _email = Container(
     padding: EdgeInsets.only(left: 10, right: 10),
     child: TextFormField(
       keyboardType: TextInputType.emailAddress,
       controller: emailContr,
       autofocus: false,
       validator: (input) {
         if(input.isEmpty)
           {
             return 'Email cannot be empty';
           }
          return null;
       },
       //onSaved: (input)=> emailid = input,
       decoration: InputDecoration(
         hintText: 'Enter Email Address',
         suffixIcon: Icon(Icons.email),
         border: OutlineInputBorder(
             borderRadius: BorderRadius.circular(10)
         ),
       ),
     ),
   );

   final _pass = Container(
     padding: EdgeInsets.only(left: 10, right: 10),
     child: TextFormField(
       controller: passwordContr,
       obscureText: true,
       autofocus: false,
       validator: (input) {
         if(input.length <= 6)
         {
           return 'Password should be at least 6 characters';
         }
         return null;
       },
       decoration: InputDecoration(
         hintText: 'Enter password',
         suffixIcon: Icon(Icons.lock),
         border: OutlineInputBorder(
             borderRadius: BorderRadius.circular(10)
         ),
       ),
     ),
   );

  /*final login_button =

    },
  );
   */

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.yellow,
      body: Container(
        child: Form(
          key: formkey,
          child: Column(
            children: <Widget>[
              SizedBox(height: 200,),
              Text('Vibing',
                style:TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 64,
                ),
              ),
              SizedBox(height: 100,),
              _email,
              SizedBox(height: 20,),
              _pass,
              SizedBox(height:30),
              RaisedButton(

                  color: Colors.yellow,
                  elevation: 5,
                  child: Text('Login'),
                  onPressed: (){
                    _validateAndSubmit();
                    formkey.currentState.reset();
                  }
              ),
              SizedBox(height:10),
              FlatButton(
                  child: Text('Forgot password'),
                  onPressed: ()=> Navigator.push(context, MaterialPageRoute(builder:(context)=>ForgotPassword()),)
              ),
              SizedBox(height:10),
              FlatButton(
                  child: Text('New? Register here!'),
                  onPressed: ()=> Navigator.push(context, MaterialPageRoute(builder:(context)=>UserReg()),)
              ),
            ],
          ),
        ),
        ) ,
      );
  }

}

Ответы [ 2 ]

1 голос
/ 14 июля 2020

reset(): Сбрасывает каждый [FormField], который является потомком этой [Form], обратно в его [FormField.initialValue].

В вашем случае initialValue является пустой строкой "", и поэтому, когда вы вызывали метод reset() of Form, он устанавливает пустую строку, которая не покажет никакой ошибки, так как там ничего нет.

1 голос
/ 14 июля 2020

Проблема в том, что вы сбрасываете форму после проверки, поэтому любая отображаемая ошибка будет сброшена. Просто удалите эту строку из обратного вызова кнопки входа:

formkey.currentState.reset();

И вуаля:

введите описание изображения здесь

...