11

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?

2 Answers 2

28

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank u very much :) or you can do; final Function xx; and when using; await(xx() as Future<void>);
I couldn't find an explanation on this syntax ANYWHERE on the internet. I just wanted to ask for confirmation, Future<void> is what the object of class Function returns, and Function() <- these parentheses contain the arguments for the Function, is that correct?
@Cedric Yes, that is correct. Think of it as declaring a function without a body, replacing the function name with "Function", and appending a variable name. The Function type can specify the typical type params (generics), params, named params, optional params. See the spec section 9.3 Type of a Function for more info.
I was about to open a new question, It did help, thank you
0

Like this

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,
    );
  }
}

2 Comments

Thanks for the quick answer. What I want to do is to use the .then() when calling the function. But asyncFunc in MyWidget is not recognized as a async function so I can't use asyncFunc().then(...). Is that possible? Thanks again.
oh.. declare the method as Future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.