firebase - 如何使用 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 类型的案例?
解决方案
我能够弄清楚这一点。我将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;
}
}
}
推荐阅读
- python - Python如何使用具有不同长度的verctors的箱线图创建一个图
- .net-core - 登录时在启动类中注册服务
- android - React-Native (Android) - 任务 ':app:transformClassesWithMultidexlistForRelease' 执行失败
- angular - 使用迷你图标变体从末端位置打开 mat-sidenav
- javascript - 我的 WordPress 网站的特定页面上的页面加载时间缓慢的问题
- angular - 无法格式化角度时间戳
- c++ - OpenGL:mat4x4 与 vec4 相乘得到 tvec
- macos - 在 Mac 上调试 IE11
- c# - Entity Framework Core LINQ 麻烦创建(选择案例存在)查询
- c# - 将笔记本电脑连接到多台显示器时出现显示器编号问题