flutter - “onError”处理程序无法返回“Null”类型的值
问题描述
我无法从 dart Future 的 catchError 处理程序返回 null。我可以使用 try catch 来做到这一点,但我需要使用 then catchError。
使用尝试捕获
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
返回的地方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
}
如果你不能改变someFuture
方法的返回类型,我们也可以这样做,我们基于另一个未来创建一个新的未来,但我们指定我们的类型是可空的:
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
}
推荐阅读
- java - @PostConstruct 和 Autowired 构造函数有什么区别?
- python - Sublime Text 3 不再访问环境变量
- vue.js - mapActions not returning action from module
- r - 如何按两列中的因子级别分组并输出显示R中每个级别总和的新列?
- c# - How do I create a System.IO.Stream from blob:https://localhost:5001/2b28e86c-fef1-482e-ae16-12466e6f729f
- python - 如何使用带有熊猫的for循环附加列?
- sas - SAS DO 循环输出
- linux - 使用 ansible 安装驱动器时出现“不是目录”错误
- python - 如何将图片添加到 DetailView 模板?
- azure-devops - Azure 管道中部署作业的审批信息