Search code examples
flutterdartdart-null-safety

How to return a non-nullable type from a Function in a function callback?


Future<int> getInt() async { // Error: 
  final c = Completer<int>();
  await foo.bar(
    callback1: (i) => c.complete(i),
    callback2: (j) => c.complete(j),
    error: (e) => throw e,
  );
}

The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.

As I know one of these callback will work, so how do I tell the analyzer that I've handled all the scenarios?

Note: I know I can simply use Future<int?> but I want to know if there are other ways of handling this case?


Solution

  • Analyzer is right here, you're just not returning anything from getInt().

    Add return completer.future at the end of getInt().

    Note: Using Completer here seems rather odd, it's mainly used to bridge between callback-based API and Future-based API.