Ked*_*rki 7 asynchronous dart flutter
我无法从 dart Future 的 catchError 处理程序返回 null。我可以使用 try catch 来做到这一点,但我需要使用 then catchError。
使用尝试捕获
Future<bool?> test() async {
try {
return await someFuture();
} catch (e) {
return null;
}
}
// Works without error
Run Code Online (Sandbox Code Playgroud)
但是当使用then时catchError
Future<bool?> test() {
return someFuture().catchError((e) {
return null;
});
}
// Error: A value of type 'Null' can't be returned by the 'onError' handler because it must be assignable to 'FutureOr<bool>'
Run Code Online (Sandbox Code Playgroud)
如果使用 then 和 catchError 遇到错误,如何返回 null?
这个例子适用于我已经someFuture返回的地方bool?:
Future<bool?> someFuture() async {
throw Exception('Error');
}
Future<bool?> test() {
return someFuture().catchError((Object e) => null);
}
Future<void> main() async {
print('Our value: ${await test()}'); // Our value: null
}
Run Code Online (Sandbox Code Playgroud)
如果您无法更改someFuture方法的返回类型,我们也可以这样做,我们基于另一个 future 创建一个新的 future,但我们指定我们的类型可以为 null:
Future<bool> someFuture() async {
throw Exception('Error');
}
Future<bool?> test() {
return Future<bool?>(someFuture).catchError((Object e) => null);
}
Future<void> main() async {
print('Our value: ${await test()}'); // Our value: null
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6700 次 |
| 最近记录: |