In flutter, we can declare a function as variable and call it like this
MyWidget((){print('HI');});
class MyWidget extends StatelessWidget{
final Function sayHi;
MyWidget(this.sayHi);
@override
Widget build(BuildContext context) {
sayHi();
return ...
}
}
But what if sayHi()
is a async function? How to declare a async function as variable? There seems no class like AsyncFunction
. So how to achive that?
Here, the function variable type just needs to specify that it returns a 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();
You can declare an async function by adding an async keyword before the function body. 1 We don't need to explicitly return Future. value(1) here since async does the wrapping. If you try to remove the async keyword, you will get the following error.
An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.
Defining Variables One of many ways, and the simplest way, to define a variable in Dart is using the var key word. var message = 'Hello, World'; This example creates a variable called message , and also initializes the variable with a String value of Hello, World .
Async functions are normal functions with some sugar on top. Here, the function variable type just needs to specify that it returns a 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();
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With