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

kjthegm6  于 2022-11-30  发布在  Flutter
关注(0)|答案(5)|浏览(151)

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

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

    }
  }
}

这将是真正有帮助的,如果有人也帮助我在验证正确的电子邮件格式,并给予适当的验证密码

vlf7wbxs

vlf7wbxs1#

如果尝试不成功,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);
});

出于安全考虑,我建议将一些邮件合并在一起,而不是给可能的攻击者一个提示,告诉他们电子邮件是否已经在系统中。
我不知道如何使用Flutter,所以我只能给一个想法;
在这里,您直接尝试从方法取得使用者。

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

相反,我会建议使用这样的东西(这是有Angular 的,但我认为你可以很容易地适用于Flutter与一些修改)

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

7d7tgy0s

7d7tgy0s2#

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

希望能帮上忙。

cxfofazt

cxfofazt3#

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

dgsult0t4#

你需要捕捉具体的错误。我自己有问题,用这个代码我解决了问题。

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

5lwkijsr5#

1.添加rflutter_alert:^2.0.4,位于项目文件pubspec.yaml的依赖项下:并保存它
1.将import 'package:rflutter_alert/rflutter_alert.dart';添加到验证屏幕的文件中
1.加了
警报(上下文:上下文、标题:"登录失败",说明:"电子邮件或密码不正确。"). 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();
      }

    }

相关问题