【发布时间】: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