how to display an error message if email and password is not valid in firebase flutter?

firebase auth error codes
firebase auth error handling
firebase auth error handling flutter
flutter firebase check if user is logged in
flutter firebase platformexception
firebase email authentication flutter
flutter firebase auth
firebase auth/invalid email

i have developed an login page,if the email and password matches from the database it successfully login's and moves to the new page,but if its wrong i want to display an error message email or password doesn't match.

Here's my code:

class _AdminLoginState extends State<AdminLogin> {
  String _username, _password;
  TextEditingController _email = TextEditingController();


  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('LOGIN'),
        backgroundColor: Colors.indigo[900],


      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.only(top: 50),
              child: SizedBox(
                height: 150.0,
                width: 300,
                child: Image.asset("assets/admin.png",
                  fit: BoxFit.contain,),


              ),
            ),
            Container(

              child: Text("ADMIN",style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold,color: Colors.indigo),),

            ),
            Container(
              padding: const EdgeInsets.only(bottom: 50),
              child: Column(
                children: <Widget>[
                  SingleChildScrollView(

                    child: Form(
                      key: _formkey,
                      child: Column(
                        children: <Widget>[
                          SizedBox(
                            height: 60,
                          ),

                          SizedBox(
                            width: 380,
                            height: 70,
                            child: Container(
                              padding: EdgeInsets.all(4),
                              width: 500,
                              height: 60,
                              child: TextFormField(
                                autofocus: false,
                                obscureText: false,
                                keyboardType: TextInputType.emailAddress,
                                validator:(input){
                                  if(input.isEmpty){
                                    return 'please type username';
                                  }
                                  return null;
                                },
                                onSaved: (input) => _username =input ,
                                decoration: InputDecoration(
                                    labelText: 'Email',
                                    hintText: "Email",
                                    labelStyle: TextStyle(
                                      color: Colors.black,
                                      fontSize: 16,
                                    ),
                                  border: new OutlineInputBorder(
                                    borderRadius: const BorderRadius.all(

                                      const Radius.circular(20.0),
                                    ),
                                  ),
                                ),


                              ),
                            ),
                          ),

                          SizedBox(
                            width: 380,
                            height: 70,
                            child: Container(
                              padding: EdgeInsets.all(4),
                              width: 400,
                              height: 60,
                              child: TextFormField(
                                autofocus: false,
                                obscureText: true,
                                validator:(input){
                                  if(input.isEmpty){
                                    return 'please type Password';
                                  }
                                  return null;
                                },
                                onSaved: (input) => _password =input ,
                                decoration: InputDecoration(
                                    labelText: 'Password',
                                    hintText: "Password",
                                    labelStyle: TextStyle(
                                      color: Colors.black,
                                      fontSize: 16,
                                    ),
                                  border: new OutlineInputBorder(
                                    borderRadius: const BorderRadius.all(
                                      const Radius.circular(20.0),
                                    ),
                                  ),
                                ),


                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.all(4),
                            width: 500,
                            height: 60,
                            child: RaisedButton(
                              onPressed: login,
                              textColor: Colors.white,
                              color: Colors.indigo[900],
                              child: Text('Login'),
                            ),
                          )


                        ],
                      ),
                    ),
                  ),


                ],


              ),
            ),

          ],

        ),
      ),
      );

  }
  Future<void> login() async{
    final  formState = _formkey.currentState;
    if(formState.validate()){
      formState.save();
      try{

        final FirebaseUser user = (await FirebaseAuth.instance.signInWithEmailAndPassword(email: _username, password: _password)).user;
        Navigator.push(context, MaterialPageRoute(builder: (context) => Admin()));
      }catch(e){
        print(e.message);
      }


    }
  }
}

it will be really helpful if someone also helps me in validating the right email format and give give the proper validation for password

signInWithEmailAndPassword() returns an exception with a special code if the attempt is unsuccessful.

In order to print a message you need to add a catch block to your signInWithEmailAndPassword() method. Then you can use the error message.

Example:

firebase.auth().signInWithEmailAndPassword(email, password)
    .catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  if (errorCode === 'auth/wrong-password') {
    alert('Wrong password.');
  } else {
    alert(errorMessage);
  }
  console.log(error);
});

For security purposes I would suggest combining some of the messages together instead of giving a possible attacker a hint about if the email is already in the system or not.

I do not know how to use flutter so I can only give an idea;

In here you are directly trying to get the user from the method.

final FirebaseUser user = (await FirebaseAuth.instance.signInWithEmailAndPassword(email: _username, password: _password)).user;

Instead I would suggest using something like this (this is angular but I think you can easily apply to flutter with some modification)

final FirebaseUser user;

 await firebase.auth().signInWithEmailAndPassword(email, password)
      .then((data) => {
          this.user = data.user;
      })
      .catch((error) => {
        switch (error.code) {
          case "auth/invalid-email":
          case "auth/wrong-password":
          case "auth/user-not-found":
            {
              this.accountErrorMessage = "Wrong email address or password.";
              break;
            }
          case "auth/user-disabled":
          case "user-disabled":
            {
              this.accountErrorMessage = "This account is disabled";
              break;
            }
        }

You can find which kind of errors it may return from here: https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html#signinwithemailandpassword

Admin Authentication API Errors, Here is a full list of the error codes and descriptions, including See Initialize the SDK for documentation on how to authenticate the Admin SDKs auth/invalid- email, The provided value for the email user property is invalid. auth/invalid-id- token, The provided ID token is not a valid Firebase ID token. I'm trying to build a login page with firebase auth plugin. But I don't know how to handle auth errors in a cross-platform way. For example, this are some PlatformException that I get when the user type the wrong password/email or there

Use errortext in InputDecoration

here is demo

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            TextField(
              controller: _text,
              decoration: InputDecoration(
                labelText: 'email',
                errorText: loginfail ? 'email not match' : null,
              ),
            ),
            TextField(
              controller: _text,
              decoration: InputDecoration(
                labelText: 'password',
                errorText: loginfail ? 'password not match' : null,
              ),
            ),
            RaisedButton(
              onPressed: () {
                login();
              },
              child: Text('Submit'),
              textColor: Colors.white,
              color: Colors.blueAccent,
            )
          ],
        ),
      ),
    );
  }

Future<void> login() async{
    final  formState = _formkey.currentState;
    if(formState.validate()){
      formState.save();
      try{

        final FirebaseUser user = (await FirebaseAuth.instance.signInWithEmailAndPassword(email: _username, password: _password)).user;
        if(!user.uid.isEmpty()){
         Navigator.push(context, MaterialPageRoute(builder: (context) => Admin()));
        }else{
         setState((){
           loginfail = true; //loginfail is bool
          });
        }

      }catch(e){
        print(e.message);
      }
    }

hope it helps..

How to handle firebase auth errors? � Issue #20223 � flutter/flutter , But I don't know how to handle auth errors in a cross-platform way. that I get when the user type the wrong password/email or there GitHub is home to over 50 million developers working together to host and review code, manage NetworkError; break; // default: print('Case ${e.message} is not jet� Make sure that there is a value if not then the field is invalid and we will turn the message otherwise we return null indicating that is valid. 3. Create a button to validate and submit of the Form. Finally, we can call the validate function and then we submit the data.

Following @Jaydeepchatrola answer's

I used a try catch block and checked if password was invalid or email, for better results!

               try {
                    setState(() {
                      wrongEmail = false;
                      wrongPassword = false;
                    });
                    final newUser = await _auth.signInWithEmailAndPassword(
                        email: email, password: password);
                    if (newUser != null) {
                      Navigator.pushNamed(context, Done.id);
                    }
                  } catch (e) {
                    print(e.code);
                    if (e.code == 'ERROR_WRONG_PASSWORD') {
                      setState(() {
                        wrongPassword = true;
                      });
                    } else {
                      setState(() {
                        emailText = 'User doesn\'t exist';
                        passwordText = 'Please check your email';

                        wrongPassword = true;
                        wrongEmail = true;
                      });
                    }
                  }

(Ep 20) How to Add Form Validation and Alert User of Firebase Auth , After that, we'll explore how to display error messages returned fr (Ep 20) How to Add Form Duration: 19:08 Posted: Jul 29, 2019 Flutter & Firebase. In this article, I will be explaining how you can use FirebaseAuth to authenticate users of your app, using the Email and Password method, and store their information in the

Flutter : How to do user login with Firebase, 23/07/19 — Added trim method to email and password value We will use bool _isLoading to determine whether to show the CircularProgressIndicator or not. Next, we are build UI to display error messages to user. Here is the part, on showing user the correct page according to their AuthStatus. Dismiss Join GitHub today. GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.

Using Firebase Authentication, To create a new Firebase Auth instance, call the instance getter on FirebaseAuth : can handle any errors which are thrown from the method, view the Error Handling Email/Password is a common user sign in method for most applications. create the new account (if it does not already exist and the password is valid)� If you haven't yet connected your app to your Firebase project, do so from the Firebase console. Enable Email/Password sign-in: In the Firebase console, open the Auth section. On the Sign in method tab, enable the Email/password sign-in method and click Save. Create a password-based account

Build a form with validation, For example, you might require users to log in with an email address and password If the user submits incorrect information, display a friendly error message Note: This is a `GlobalKey<FormState>`, // not a GlobalKey< MyCustomFormState>. If the user's input isn't valid, the validator function returns a String containing� The password hash must be a valid byte buffer. auth/invalid-password-salt: The password salt must be a valid byte buffer auth/invalid-phone-number: The provided value for the phoneNumber is invalid. It must be a non-empty E.164 standard compliant identifier string. auth/invalid-photo-url: The provided value for the photoURL user property is

Comments
  • can you suggest me how can i use this set lines in my code please
  • should i replace these entire lines with that single line?
  • that code firebase.auth() i'm not able to include in my codes its throwing an exception
  • it's angular code, you need to change it for your language FirebaseAuth.instance. probably
  • i'm seriously new to flutter can you help me in it i don't know how to do it\
  • should i declare loginfail as false in the beginnig
  • this way, you are not going to know what is the reason for the fail and it will show the error for both of the fields. Two errors may confuse users because even if just the password is wrong, error says email is wrong as well.
  • debug what you get in user var
  • can you tell me how to do that?
  • rohit bhai just add print(user);