firebase - FirabaseAuth 无法在 Flutter 中捕获异常
问题描述
我正在为我的应用程序创建一个注册屏幕。我实现了firebase,可以对用户进行身份验证并将一些用户信息成功保存到firebase数据库中。我开始检查 userName 字段是否为空。但是firebase有时无法捕获格式错误的电子邮件地址的异常。它每次都适用于密码(最少 6 个字符),但有时适用于电子邮件。我找不到任何解决方案。这是我的代码。有没有人有想法?
onPressed: () async {
if (validateName(userName) && validateEmail(email)) {
setState(() {
showSpinner = true;
});
try {
final newUser =
await _auth.createUserWithEmailAndPassword(
email: email, password: password);
if (newUser != null) {
//get name and update user profile
UserUpdateInfo userUpdateInfo = UserUpdateInfo();
userUpdateInfo.displayName = userName;
FirebaseUser user = await _auth.currentUser();
await user.updateProfile(userUpdateInfo);
await user.reload();
Navigator.pushNamed(context, NavigationScreen.id);
}
setState(() {
showSpinner = false;
});
} on PlatformException catch (e) {
setState(() {
showSpinner = false;
});
Fluttertoast.showToast(
msg: e.message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 3,
backgroundColor: Colors.white,
textColor: Colors.red,
fontSize: 18.0,
);
}
} else {
Fluttertoast.showToast(
msg: 'You must ente all information',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 3,
backgroundColor: Colors.white,
textColor: Colors.red,
fontSize: 18.0,
);
}
},
//name TextField validation
bool validateName(String name) {
if (name != null && name.length > 2) {
return true;
} else {
return false;
}
}
//email TextField validation
bool validateEmail(String email) {
if (email != null) {
return true;
} else {
return false;
}
}
解决方案
createUserWithEmailAndPassword
返回 a Future<AuthResult>
,要捕获错误,您可以执行以下操作:
final newUser = await _auth.createUserWithEmailAndPassword(email: email, password: password).catchError((err) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text(err.message),
actions: [
FlatButton(
child: Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
使用catchError
,它将处理此 Future 发出的错误,然后showDialog
将显示一个包含错误的对话框。
推荐阅读
- ios - 在 AppStore Connect 中选择什么?我的应用程序是否使用加密?
- swift - 如何在 Swift 中使用保护子句,让代码更干净
- powershell - Powershell how to loop through individual files in a directory
- android - 在 Android 中从一个 Activity 移动到另一个 Activity,而无需创建不必要的 Activity
- python - 如何打印通过输入给出的列表中的项目?
- user-interface - 一次制作多个 GUI,但这需要很长时间!我怎样才能更快地做到这一点
- c# - 在 winForm 函数之外调用函数
- r - 使用 lapply 在 R 中逐列将某个值的所有元素更改为另一个值
- wordpress - 重力形式计算器间隔
- ruby-on-rails - 带有 PostgreSQL 的 Rails 5 将表关系从多态更改为标准 has_one/belongs_to 关联