0

I have a function, which I want to return a Future of String or null. For simplicity, the function will return null if delay for 1 second is success, or else it will return "failed";

However; I got the

  Future<String?> fcn(String str) {
    return Future.delayed(const Duration(seconds: 1)).then((value) {
      return null;
    }).onError((error, stackTrace) {
      return "failed"; // The return type 'String' isn't a 'FutureOr<Null>', as required by the closure's context.
    });
  }
Steven Z.
  • 47
  • 1
  • 11

1 Answers1

0

Try to use onError as parameter of then method:

Future<String?> fcn(String str) {
  return Future.delayed(const Duration(seconds: 1)).then((value) {
    return null;
  }, onError: (error, stackTrace) {
    return "failed";
  });
}

Or method catchError:

Future<String?> fcn(String str) {
  return Future.delayed(const Duration(seconds: 1)).then((value) {
    return null;
  }).catchError((error, stackTrace) {
    return "failed";
  });
}
Sergio
  • 27,326
  • 8
  • 128
  • 149
  • Thank you that worked, but why is that? – Steven Z. Oct 18 '21 at 20:36
  • It is strange that you don't get another error: "The method 'onError' isn't defined for the type 'Future" bcz there is no `onError` method defined in `Future` class https://api.dart.dev/stable/2.14.4/dart-async/Future-class.html – Sergio Oct 18 '21 at 20:57