![](/img/trans.png)
[英]Flutter : How to declare async function as a variable in Dart?
[英]How to declare async function as a variable in flutter(dart)?
在flutter中,我们可以将一个函数声明为变量并像这样调用它
MyWidget((){print('HI');});
class MyWidget extends StatelessWidget{
final Function sayHi;
MyWidget(this.sayHi);
@override
Widget build(BuildContext context) {
sayHi();
return ...
}
}
但是如果sayHi()
是一个异步函数呢? 如何将异步函数声明为变量? 似乎没有像AsyncFunction
这样的AsyncFunction
。 那么如何实现呢?
异步函数是普通函数,上面有一些糖。 这里,函数变量类型只需要指定它返回一个 Future:
class Example {
Future<void> Function() asyncFuncVar;
Future<void> asyncFunc() async => print('Do async stuff...');
Example() {
asyncFuncVar = asyncFunc;
asyncFuncVar().then((_) => print('Hello'));
}
}
void main() => Example();
希望这可以帮助。
像这样
class MyApp extends StatelessWidget {
void asyncFunc() async {
await Future.delayed(Duration(seconds: 5));
print('printed after 5 seconds');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(asyncFunc),
),
),
);
}
}
class MyWidget extends StatelessWidget {
final void Function() asyncFunc;
const MyWidget(this.asyncFunc);
@override
Widget build(BuildContext context) {
return MaterialButton(
onPressed: asyncFunc,
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.