首页 > 解决方案 > FirabaseAuth 无法在 Flutter 中捕获异常

问题描述

我正在为我的应用程序创建一个注册屏幕。我实现了firebase,可以对用户进行身份验证并将一些用户信息成功保存到firebase数据库中。我开始检查 userName 字段是否为空。但是firebase有时无法捕获格式错误的电子邮件地址的异常。它每次都适用于密码(最少 6 个字符),但有时适用于电子邮件。我找不到任何解决方案。这是我的代码。有没有人有想法?

 onPressed: () async {
    if (validateName(userName) && validateEmail(email)) {
      setState(() {
        showSpinner = true;
      });
      try {
        final newUser =
            await _auth.createUserWithEmailAndPassword(
                email: email, password: password);
        if (newUser != null) {
          //get name and update user profile
          UserUpdateInfo userUpdateInfo = UserUpdateInfo();
          userUpdateInfo.displayName = userName;
          FirebaseUser user = await _auth.currentUser();
          await user.updateProfile(userUpdateInfo);
          await user.reload();

          Navigator.pushNamed(context, NavigationScreen.id);
        }
        setState(() {
          showSpinner = false;
        });
      } on PlatformException catch (e) {
        setState(() {
          showSpinner = false;
        });
        Fluttertoast.showToast(
          msg: e.message,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.white,
          textColor: Colors.red,
          fontSize: 18.0,
        );
      }
    } else {
      Fluttertoast.showToast(
        msg: 'You must ente all information',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.white,
        textColor: Colors.red,
        fontSize: 18.0,
      );
    }
  },

//name TextField validation
  bool validateName(String name) {
    if (name != null && name.length > 2) {
      return true;
    } else {
      return false;
    }
  }

  //email TextField validation
  bool validateEmail(String email) {
    if (email != null) {
      return true;
    } else {
      return false;
    }
  }

标签: firebaseflutterdartfirebase-authentication

解决方案


createUserWithEmailAndPassword返回 a Future<AuthResult>,要捕获错误,您可以执行以下操作:

final newUser = await _auth.createUserWithEmailAndPassword(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();
                  },
                )
              ],
            );
          });

使用catchError,它将处理此 Future 发出的错误,然后showDialog将显示一个包含错误的对话框。


推荐阅读