首页 > 解决方案 > 如何使用 Switch 语句处理 FirebaseAuthException

问题描述

我有一个 Flutter 应用程序,允许用户使用 FirebaseAuth 注册/登录他们的帐户。登录需要用户输入他们的电子邮件地址和密码。我正在尝试使用 switch 语句来处理用户由于输入错误的电子邮件地址、错误的密码等而无法登录的情况。

下面的 login_screen.dart 包含登录按钮的代码,当按下时,会在出现 FirebaseAuthException 时调用 FirebaseAuthHandler(来自 firebase_auth_handler.dart)。

login_screen.dart

RoundedButton(
            title: 'Log In',
            colour: Colors.lightBlueAccent,
            onPressed: () async {
              setState(() {
                showSpinner = true;
              });
              try {
                final user = await _auth.signInWithEmailAndPassword(
                    email: email, password: password);
                if (user != null) {
                  Navigator.pushNamed(context, LandingScreen.id);
                }
                setState(() {
                  showSpinner = false;
                });
              } catch (errorCode) {
                FirebaseAuthHandler(errorCode).handleErrorCodes();
                setState(() {
                  showSpinner = false;
                });
              }
            },
          ),

firebase_auth_handler.dart

    class FirebaseAuthHandler {
  FirebaseAuthHandler(this.errorCode);

  FirebaseAuthException errorCode;

  handleErrorCodes() {
    switch (errorCode) {
      case "[firebase_auth/wrong-password] The password is invalid or the user does not have a password.":
        print("Invalid password.");
        break;
      case "[firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.":
        print("Invalid email address.");
        break;
    }
  }
}

问题是我收到一个关于switch(errorCode)的错误,它说,

Type 'FirebaseAuthException' of the switch expression isn't assignable to the type 'String' of case expressions

我使用的两个 case 语句是打印异常时打印到控制台的内容。如何提供适用于我的 switch 语句的 FirebaseAuthException 类型的案例?

标签: firebasefluttergoogle-cloud-firestorefirebase-authenticationswitch-statement

解决方案


我能够弄清楚这一点。我将switch(errorCode)更改为switch(errorCode.code)并将案例更改为下面的内容。我能够在此处找到 signInWithEmailAndPassword 的错误代码列表,并为 case 表达式插入了一些错误代码。

正如@rickimaru 评论的那样,您也可以使用errorCode.message而不是errorCode.code如果您愿意,只要您找到相应的消息并将其插入案例表达式即可。

class FirebaseAuthHandler {

  handleErrorCodes(FirebaseAuthException errorCode) {
    switch (errorCode.code) {
      case "wrong-password":
        print("Invalid password!!!");
        break;
      case "user-not-found":
        print("Invalid email address!!!");
        break;
    }
  }
}

推荐阅读