如何使用Switch语句处理FirebaseAuthException
我有一个Flatter应用程序,允许用户使用FirebaseAuth注册/登录他们的帐户。登录要求用户输入其电子邮件地址和密码。我试图使用switch语句来处理用户由于输入错误的电子邮件地址、密码等而无法登录的情况 下面的login_screen.dart包含登录按钮的代码,按下时,在出现FirebaseAuthException时调用FirebaseAuthHandler(从firebase_auth_handler.dart) 登录屏幕.dart如何使用Switch语句处理FirebaseAuthException,firebase,flutter,google-cloud-firestore,firebase-authentication,switch-statement,Firebase,Flutter,Google Cloud Firestore,Firebase Authentication,Switch Statement,我有一个Flatter应用程序,允许用户使用FirebaseAuth注册/登录他们的帐户。登录要求用户输入其电子邮件地址和密码。我试图使用switch语句来处理用户由于输入错误的电子邮件地址、密码等而无法登录的情况 下面的login_screen.dart包含登录按钮的代码,按下时,在出现FirebaseAuthException时调用FirebaseAuthHandler(从firebase_auth_handler.dart) 登录屏幕.dart RoundedButton(
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;
}
}
}
问题是我得到了一个关于开关(errorCode)的错误,即
Type 'FirebaseAuthException' of the switch expression isn't assignable to the type 'String' of case expressions
我使用的两个case语句是打印异常时打印到控制台的语句。我怎样才能提供一个FirebaseAuthException类型的案例来处理我的switch语句呢?我已经找到了这个案例。我将开关(errorCode)更改为开关(errorCode.code),并将案例更改为下面的内容。我能够找到一个使用Email和Password登录的错误代码列表,并为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;
}
}
}
正如@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;
}
}
}
你试过
switch(errorCode.code){
或switch(errorCode.message){
吗?@rickimaru我刚把它改成switch(errorCode.code),它消除了错误,但print语句没有触发。你知道为什么吗?