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()
?
CodePudding user response:
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
CodePudding user response:
So it turns out no need to know if it is async or not in my case. The class Future
has 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