简体   繁体   English

如果 flutter 登录表单中的密码或用户 email 错误,则返回错误消息

[英]Return error message if password or user email wrong in flutter login form

Hy Guys I have connected flutter to my firebase project and used AUTH feature in Firebase but what I would do is to show an error message when a wrong password or Email user is wrong. Hy Guys I have connected flutter to my firebase project and used AUTH feature in Firebase but what I would do is to show an error message when a wrong password or Email user is wrong. this is my code:这是我的代码:

Widget submitButton (){
    return Container(
      child: SizedBox(
        width: 220,
        height: 40,
        child: MaterialButton(
          elevation: 5,
          onPressed: () async {
            setState(() {
              showProgress = true;
            });

            try {
              final newUser = await _auth.signInWithEmailAndPassword(email: email, password: password);
              print(newUser.toString());
              if (newUser != null) {
                Navigator.push(context, PageTransition(
                  type: PageTransitionType.fade,
                  child: WelcomeScreen(),
                ));
                setState(() {
                  showProgress = false;
                });

              }
            } catch (e) {}
          },
          child: Text('Accedi',style: TextStyle(color: Colors.black),),
          color: Colors.white,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
              side: BorderSide(color: Colors.black12,width: 1)),
        ),

      ),
    );
  }

First you need to catch the error, you can do that by using catchError() :首先你需要捕获错误,你可以使用catchError()来做到这一点:

final newUser = await _auth.signInWithEmailAndPassword(email: email, password: password)
    .catchError((err) {
          showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Error"),
              content: Text(err.message),
              actions: [
                FlatButton(
                  child: Text("Ok"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                )
              ],
            );
          });
    });

Then the showDialog will have err.message which will contain the error received from Firebase Authentication.然后showDialog将具有err.message ,其中将包含从 Firebase Authentication 收到的错误。

You have two options:你有两个选择:

1.Use an alert dialog 1.使用警告对话框

  void _showAlertDialog(String message) async {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(message),
          actions: <Widget>[
            FlatButton(
              child: Text('Ok'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

full example完整的例子

  1. Use errorText property in InputDecorationInputDecoration中使用errorText属性
TextField(
    decoration: InputDecoration(
        errorText: this.errorText,
    ),
)

full example完整的例子

You can use a Form() with TextFormField()您可以将 Form() 与 TextFormField() 一起使用

Something like this:像这样的东西:

Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            TextFormField(
              key: ValueKey('email'),
              validator: (value) {
                if (value.isEmpty || !value.contains('@'))
                  return 'Please enter a valid Email address';
                return null;
              },
              keyboardType: TextInputType.emailAddress,
              decoration: InputDecoration(labelText: 'Email address'),
              onSaved: (value) {
                _userEmail = value;
              },
            ),

It's just a dummy, but as you see there's some validation code in the validator attribute.它只是一个假人,但正如您所见,validator 属性中有一些验证代码。

So what validator does is, if you return null everything is well and good, but if something is wrong, just return the String and it'll be shown below the text form field as an error message.所以验证器的作用是,如果你返回 null 一切都很好,但如果有问题,只需返回字符串,它会在文本表单字段下方显示为错误消息。

And to validate you can call a method like this to activate the method while form submission为了验证您可以调用这样的方法来激活该方法,同时提交表单

void _trySubmit() {
final bool isValid = _formKey.currentState.validate();
FocusScope.of(context).unfocus();

if (isValid) {
  _formKey.currentState.save();
  widget.submitFn(
    _userEmail.trim(),
    _userName.trim(),
    _userPassword.trim(),
    _isLogin,
    context,
  );
}}

The method for getting isValid will invoke validation function of all TextFormFields, if all of them are okay, it'll return true else it'll return false.获取isValid的方法会调用所有TextFormFields的验证function,如果都ok则返回true,否则返回false。

All the _name are used to store the values in state variables using the onSaved attribute.所有 _name 都用于使用 onSaved 属性将值存储在 state 变量中。

Let me know if you have anymore doubts.如果您还有疑问,请告诉我。

Hope this helps✌希望这有帮助✌

暂无
暂无

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

相关问题 在没有 email 密码的情况下登录 flutter - Login in flutter without email password 如果电子邮件和密码在 Firebase Flutter 中无效,如何显示错误消息? - how to display an error message if email and password is not valid in firebase flutter? 这个firebase电子邮件和密码登录有什么问题? - what is wrong with this firebase email and password login? 如何在Firebase简单登录电子邮件密码上显示错误密码的错误状态 - How to show error state for wrong password on Firebase Simple Login email password 我可以在每次用户登录时发送电子邮件验证,而不是在 firebase (Flutter) 中使用密码吗? - Can I send email verification every time the user login instead of using password in firebase (Flutter)? 使用为 Google 帐户提供“身份验证/错误密码”的电子邮件的 Firebase 登录 - Firebase login with email giving "auth/wrong-password" for a Google account 用户电子邮件和密码不匹配时如何显示错误消息 - How can I show error message when user email and password doesn't matched 如何限制Firebase电子邮件登录中的错误密码尝试? - How can i limit the wrong password attempts in Firebase email login? 使用 Flutter Firebase email 和密码验证登录有问题 - Having problem with login with Flutter Firebase email and password authentication Swift 3 Firebase用户身份验证/使用电子邮件密码登录数据库 - Swift 3 Firebase user authentication / database login with email password
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM