A value of type 'Null' can't be returned by the 'onError' handler

2,533

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;
});

}

Share:
2,533
Kedar Karki
Author by

Kedar Karki

Updated on December 22, 2022

Comments

  • Kedar Karki
    Kedar Karki over 1 year

    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?

    • julemand101
      julemand101 almost 3 years
      The type of someFuture needs to be able to return null since catchError just gets the same return type as someFuture.
    • Kedar Karki
      Kedar Karki almost 3 years
      Making someFuture able to return null gives same error in runtime whereas previously it gave warning on compile time.