【问题标题】:How to Use Switch Statement To Handle FirebaseAuthException如何使用 Switch 语句处理 FirebaseAuthException
【发布时间】:2021-08-18 14:53:00
【问题描述】:

我有一个 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 类型的案例?

【问题讨论】:

  • 你试过switch (errorCode.code) {switch (errorCode.message) {吗?
  • @rickimaru 我只是将其更改为 switch(errorCode.code) 并消除了错误,但打印语句没有触发。知道为什么吗?

标签: firebase flutter google-cloud-firestore firebase-authentication switch-statement


【解决方案1】:

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

正如@rickimaru 评论的那样,您也可以根据需要使用 errorCode.message 代替 errorCode.code,只要找到相应的消息并将其插入即可对于 case 表达式。

class FirebaseAuthHandler {

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

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 1970-01-01
    • 2011-06-26
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2021-02-28
    相关资源
    最近更新 更多