Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare async function as a variable in flutter(dart)?

Tags:

flutter

dart

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?

like image 693
Josh Chiu Avatar asked Jan 18 '20 05:01

Josh Chiu


People also ask

How do you declare async as a variable in Dart?

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();

How do you make async function in Flutter?

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.

How does async work in Dart?

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.

How do you set variables in Flutter?

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 .


Video Answer


1 Answers

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.

like image 60
hola Avatar answered Nov 14 '22 17:11

hola