firebase - Flutter - UI 上的 Firebaser PlatformException 处理(ERROR_EMAIL_ALREADY_IN_USE,电子邮件地址已被另一个帐户使用。,null))
问题描述
我完成了 UI 以处理身份验证中的一些错误消息。
我在 API 中放置了 catch 错误以进行注册(登录也是如此)
signup(User user, AuthNotifier authNotifier) async {
try{
AuthResult authResult = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: user.email, password: user.password)
.catchError((error) => print(error.code));
if (authResult != null) {
UserUpdateInfo updateInfo = UserUpdateInfo();
updateInfo.displayName = user.displayName;
FirebaseUser firebaseUser = authResult.user;
if (firebaseUser != null) {
await firebaseUser.updateProfile(updateInfo);
await firebaseUser.reload();
print("Sign up: $firebaseUser");
FirebaseUser currentUser = await FirebaseAuth.instance.currentUser();
authNotifier.setUser(currentUser);
}
}}catch (e) {
print('Failed with error code: ${e.code}');
print(e.message);}
}
当我添加由错误消息和验证触发的小部件时,用户可以看到错误。
bool validate() {
final form = _formKey.currentState;
form.save();
if (form.validate()) {
form.save();
return true;
} else {
return false;
}
}
submitForm() {
if (validate())
{
try{
AuthNotifier authNotifier = Provider.of<AuthNotifier>(context, listen: false);
if (_authMode == AuthMode.Login) {
login(_user, authNotifier);
} else if (_authMode == AuthMode.Signup) {
signup(_user, authNotifier);
return Navigator.of(context).pushReplacement(
new MaterialPageRoute(
builder: (BuildContext context) {
return SecondPage();
},
),
);
}
} catch (e) {
setState(() {
_warning = e.message;
});
}
}
}
Widget _showAlert() {
if (_warning != null) {
return Container(
color: Colors.amberAccent,
width: double.infinity,
padding: EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Icon(Icons.error_outline),
),
Expanded(
child: AutoSizeText(
_warning,
maxLines: 3,
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: IconButton(
icon: Icon(Icons.close),
onPressed: () {
setState(() {
_warning = null;
});
},
),
)
],
),
);
}
return SizedBox(
height: 0,
);
}
尽管所有的实现都是为了捕捉错误,但错误并没有在 UI 中被正确捕捉。诸如 PlatformException(ERROR_EMAIL_ALREADY_IN_USE, etc..) 之类的消息不会在 Showalert 小部件上传递。
解决方案
您应该抛出错误而不是打印它,以便 try/catch 可以捕获它。
void main() async {
await yourFunc();
}
Future<void> someFuncThrowsError() async {
throw Error();
}
Future<void> someFuncCaller() async {
try {
await someFuncThrowsError().catchError((e) {
throw e;
});
} catch (e) {
print(e.toString());
print('try catch');
rethrow;
}
}
Future<void> yourFunc() async {
try {
await someFuncCaller();
} catch (e) {
//set warning
print('caught');
}
}
推荐阅读
- php - 链接怎么会消失?
- vue.js - 重置 v-autocomplete 中的选择值,以便添加多个项目
- angular - 禁用 mediaStream 上的视频轨道也禁用 webrtc 中的音轨
- python - 如何从“span”内的html“类”中获取/抓取所有元素?
- shared-libraries - 将共享库作为可执行文件运行?
- mysql - LIKE 比 MySQL 中的 FULLTEXT 搜索更快
- terminal - 看到以前在 Scrapy Shell 中的输入了吗?
- python - Pandas [如何将 csv 文件的所有列附加到一个中]
- azure - 使用 ADF 的 SAP Business One
- c# - 如何创建自然语言计算器