Rohit Varma
Rohit Varma

Reputation: 317

Flutter Textform Validation not showing up

I have watched a couple of tutorials on how to make validators work but none of them seemed to work. Can anyone help me with this? This is the code of a simple sign in page. My validators don't show up on screen if there's any sort of error it should be detecting. I've watched tutorials where it shows up in red but in my app, it doesn't show up at all.

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

}

Upvotes: 0

Views: 199

Answers (2)

Jitesh Mohite
Jitesh Mohite

Reputation: 34180

reset():
Resets every [FormField] that is a descendant of this [Form] back to its [FormField.initialValue].

In your case, the initialValue is empty string "" and that's why when you called reset() method of Form, it's setting an empty string, that will not show any error, as nothing is there.

Upvotes: 1

Hossein Yousefi
Hossein Yousefi

Reputation: 994

The problem is that you're resetting the form after validation so any error shown will reset. Just remove this line from your login button callback:

formkey.currentState.reset();

And voila:

enter image description here

Upvotes: 1

Related Questions