Reputation: 1805
I want to ask user for a callback function (shortened):
Future<dynamic> myfunc(dynamic onSuccess) async {
Completer c = Completer();
// some time-consuming procedure
if (onSuccess is Function) {
c.complete(true);
return c.future.then(onSuccess());
} else {
c.complete(false);
return c.future;
}
}
bool should_be_true = await myfunc(print("Success!"))
But my code does not work, dartanalyzer throws a following error on the last line:
error • The expression here has a type of 'void', and therefore cannot be used at example/index.dart:15:35 • use_of_void_result
Upvotes: 0
Views: 221
Reputation: 6161
Some comments:
print
, not a function. Use () => print('...')
to pass in a function.Future
, you want to return ASAP so you're not blocking your caller. This is why I use scehduleMicrotask
. In general, you should not need to use Completer
, except for very complex async work. Try to just use async/await.Completer
with async
.Try this:
import 'dart:async';
Future<dynamic> myfunc(dynamic onSuccess) {
var c = Completer();
scheduleMicrotask(() {
// some time-consuming procedure
if (onSuccess is Function) {
onSuccess();
c.complete(true);
} else {
c.complete(false);
}
});
return c.future;
}
main() async {
var should_be_true = await myfunc(() => print("Success!"));
}
Upvotes: 1