繁体   English   中英

如果电子邮件和密码在 Firebase Flutter 中无效,如何显示错误消息?

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

我已经开发了一个登录页面,如果数据库中的电子邮件和密码匹配它成功登录并移动到新页面,但如果它错误我想显示错误消息电子邮件或密码不匹配。

这是我的代码:

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);
      }


    }
  }
}

如果有人也帮助我验证正确的电子邮件格式并提供正确的密码验证,那将非常有帮助

如果尝试不成功,signInWithEmailAndPassword() 将返回带有特殊代码的异常。

为了打印一条消息,您需要在您的 signInWithEmailAndPassword() 方法中添加一个 catch 块。 然后您可以使用错误消息。

例子:

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);
});

出于安全目的,我建议将一些消息组合在一起,而不是向可能的攻击者提示电子邮件是否已经在系统中。

我不知道如何使用颤振,所以我只能提供一个想法;

在这里,您直接尝试从该方法中获取用户。

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

相反,我建议使用这样的东西(这是有角度的,但我认为您可以通过一些修改轻松地应用于颤振)

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;
            }
        }

您可以从这里找到它可能返回的错误类型: https ://firebase.google.com/docs/reference/js/firebase.auth.Auth.html#signinwithemailandpassword

InputDecoration中使用errortext

这是演示

@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);
      }
    }

希望能帮助到你..

关注@Jaydeepchatrola 的回答

我使用了 try catch 块并检查密码是否无效或电子邮件,以获得更好的结果!

               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;
                      });
                    }
                  }

您需要捕获特定的错误。 我自己遇到了问题,用这段代码我解决了这个问题。

try {
        final user = await _auth.signInWithEmailAndPassword(
            email: email, password: password);
        if (user != null) {
          Navigator.pushNamed(context, HomeScreen.id);
        }
      } on auth.FirebaseAuthException catch (e) {
     //Here you catch the specific error 
        if (e.code == 'wrong-password') {
    //The thing that should happen if the password is incorrect
   //In my case it will the change the hinttext  
          setState(() {
            hintTextPassword = 'Password incorrect. Please try again';
            passwordHintColor = Colors.red;
          });
        } else if (e.code == 'user-not-found') {
          setState(() {
            hintTextEmail = 'No user found for that email.';
            emailHintColor = Colors.red;
          });
        }
      } catch (e) {
        print(e);
      }
  1. 在你的项目文件 pubspec.yaml 中添加 rflutter_alert: ^2.0.4 并保存

  2. 添加import 'package:rflutter_alert/rflutter_alert.dart'; 在您的身份验证屏幕文件中

  3. 添加

    警报(上下文:上下文,标题:“登录失败”,说明:“电子邮件或密码不正确。”).show();

在捕获(e)中{}

像那样:

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){
        Alert(
                                context: context,
                                title: "Failed Login",
                                desc: "Incorrect Email Or Password.")
                            .show();
      }


    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM