1

So my question would be a duplicate of this javascript question but mine is about Flutter: I have a method (it is the method add of class Bloc so I can't await it, I need to send a callback instead) that takes as parameter a Function to execute it when work is done.

void myMethod(Function onDone) async {
  onDone();//how to know if I should write this?
  await onDone();//or this?
}

How can I know when I want to execute this Function parameter if it is sync or async i.e. if I should write await onDone() or onDone()?

HII
  • 3,420
  • 1
  • 14
  • 35

2 Answers2

2

So it turns out no need to know if it is async or not in my case. The class Futurehas the constructor Future.value that takes the result of calling the callback and awaits for it automatically if it was async (i.e. if onDone() returns a Future).

From its documentation:

If value is a future, the created future waits for the value future to complete, and then completes with the same result

It can be used as: await Future.value(onDone()); .

So in conclusion I will always use await for my callback but this will solve the problem in both cases whether onDone was synchronous or asynchronous callback

HII
  • 3,420
  • 1
  • 14
  • 35
2

You can await a non-async function. The Dart linter will issue a warning if it can work out that an awaited function isn't async, but it's only a warning. You can run the below code in DartPad: callbackOne is async, callbackTwo is not.

void main() async {
  String cb1 = await callbackOne();
  String cb2 = await callbackTwo(); //Warning here
  print("cb1=$cb1 cb2=$cb2");
  await functionWithCallback(callbackOne);
  await functionWithCallback(callbackTwo);
}

Future<void> functionWithCallback(Function callback) async {
  String foo = await callback();
  print("Callback returned $foo");
}

Future<String> callbackOne() async {
  await Future.delayed(Duration(seconds: 1));
  return "One";
}

String callbackTwo() {
  return "Two";
}

Output:

cb1=One cb2=Two
Callback returned One
Callback returned Two
Pat9RB
  • 580
  • 3
  • 7
  • 1
    I don't know about dart pad's linter rules, but in android studio it looks like the linter is configured to give an error on it, that's why I thought I can't do that, actually the code even won't compile If I call `await` on a variable of type `Function` – HII Oct 08 '21 at 22:38
  • FWIW - Just tested in vscode on Linux using "Dart from Flutter 2.5.1" and using dart cli -> The vscode linter doesn't actually issue a warning and the code runs without any error. – Pat9RB Oct 11 '21 at 00:39