【发布时间】:2021-08-28 05:03:32
【问题描述】:
我无法从 dart Future 的 catchError 处理程序返回 null。我可以使用 try catch 来完成,但我需要使用 then catchError。
使用try catch
Future<bool?> test() async {
try {
return await someFuture();
} catch (e) {
return null;
}
}
// Works without error
但是当使用 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>'
如果使用 then 和 catchError 遇到一些错误,如何返回 null?
【问题讨论】:
-
someFuture的类型需要能够返回null,因为catchError只是获得与someFuture相同的返回类型。 -
使 someFuture 能够返回 null 在运行时会产生相同的错误,而之前它会在编译时发出警告。
标签: flutter dart asynchronous