[英]Flutter - This function has a return type of 'FutureOr<XXX>', but doesn't end with a return statement
I want return a future with a value from a try catch block:我想从 try catch 块中返回一个带有值的未来:
Future<UserCredential> createUser(String email, String password) async {
try {
return FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
Get.snackbar(
'Error Creating Account', 'The password provided is too weak.',
snackPosition: SnackPosition.BOTTOM);
} else if (e.code == 'email-already-in-use') {
Get.snackbar('Error Creating Account',
'The account already exists for that email.',
snackPosition: SnackPosition.BOTTOM);
}
} catch (e) {
print(e);
Get.snackbar('Error Creating Account', e.message as String,
snackPosition: SnackPosition.BOTTOM);
}
}
But it gives this error:但它给出了这个错误:
This function has a return type of 'FutureOr<UserCredential>', but doesn't end with a return statement.此 function 的返回类型为“FutureOr<UserCredential>”,但未以返回语句结尾。 Try adding a return statement, or changing the return type to 'void'.尝试添加一个返回语句,或将返回类型更改为“void”。
Can I make this return a future that has a value in it and also handles the error in the function or do I have to change the return type to Future<void>
?我可以使它返回一个具有值的未来并处理 function 中的错误,还是我必须将返回类型更改为Future<void>
?
Your return value has to be of the type declared with the Future's generic type.您的返回值必须是使用 Future 的通用类型声明的类型。 If there are any code paths that don't return a UserCredential, then you can't use this declaration.如果有任何代码路径不返回 UserCredential,则不能使用此声明。 If you have no return value, then yes, it should be Future<void>
.如果你没有返回值,那么是的,它应该是Future<void>
。 But it seems that you do have a return value in at least one code path.但似乎您至少在一个代码路径中确实有一个返回值。
Consider instead moving all of the UI code out of this method and simply let the function throw whatever it throws (or re-throw something else).考虑将所有 UI 代码移出该方法,让 function 抛出它抛出的任何东西(或重新抛出其他东西)。 Then, make the caller of this function catch the error and decide what to show in the UI for that case.然后,让这个 function 的调用者捕获错误并决定在这种情况下在 UI 中显示什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.