我想问用户一个回调函数(简称):
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!"))
但是我的代码不起作用,dartanalyzer在最后一行抛出以下错误:
error • The expression here has a type of 'void', and therefore cannot be used at example/index.dart:15:35 • use_of_void_result
答案 0 :(得分:1)
一些评论:
print
而不是函数的结果。使用() => print('...')
传递函数。Future
的函数中,您希望尽快返回,这样就不会阻塞调用者。这就是为什么我使用scehduleMicrotask
的原因。通常,除了非常复杂的异步工作之外,您无需使用Completer
。尝试仅使用async / await。Completer
和async
来标记函数。尝试一下:
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!"));
}