首页 > 解决方案 > 如果颤振登录表单中的密码或用户电子邮件错误,则返回错误消息

问题描述

伙计们,我已经将颤振连接到我的 firebase 项目并在 Firebase 中使用了 AUTH 功能,但我要做的是在密码错误或电子邮件用户错误时显示错误消息。这是我的代码:

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)),
        ),

      ),
    );
  }

标签: firebaseflutterdartfirebase-authentication

解决方案


首先你需要捕捉错误,你可以通过使用来做到这一点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();
                  },
                )
              ],
            );
          });
    });

然后showDialogerr.message包含从 Firebase 身份验证收到的错误。


推荐阅读