'onError'处理程序无法返回类型为"Null"的值



我无法从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

但是当使用时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方法的返回类型,我们也可以这样做,我们基于另一个未来创建一个新的未来,但我们指定我们的类型可以为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
}

您应该指定someFuture((签名,它可能返回Future<bool>

Future<bool> someFuture() async

方法catchError必须返回与调用它时相同的未来类型。您可以通过将值转发到then并将其转换为Future<bool?>:来克服这一问题

Future<bool?> test() {
return someFuture()
.then((value) => Future<bool?>.value(value))
.catchError((e) {
return null;
});

}

相关内容

最新更新