I can't return a null from catchError handler of dart Future. I can do it using try catch but I need to use then catchError.
Using try catch
Future<bool?> test() async {
try {
return await someFuture();
} catch (e) {
return null;
}
}
// Works without error
But when using 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>'
How do I return null if I encounter some error using then and catchError?
Solution 1: julemand101
This example works where I have made someFuture
to return 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
}
If you can't change the return type of the someFuture
method we can also do this where we creates a new future based on another future but where we specify that our type is nullable:
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
}
Solution 2: mip
You should specify someFuture() signature, which probably returns Future<bool>
Future<bool> someFuture() async
Method catchError
must return the same future type it is called on. You can overcome this by forwarding the value to then
and convert it to Future<bool?>
:
Future<bool?> test() {
return someFuture()
.then((value) => Future<bool?>.value(value))
.catchError((e) {
return null;
});
}