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

Issue

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.

Answered By – mfkw1

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *