Home > Back-end >  Invoke async method on button click Flutter
Invoke async method on button click Flutter

Time:11-08

I have for example this future function:

Future<void> sayHello() async {
   await service.sayHello();
}

And I want to invoke it on button click

ElevatedButton(
    onPressed: () => sayHello(),
    child: const Text("Click"),
)

My question is, should onPressed be async when I want to invoke future function on clicked? Could it be async anyway?

CodePudding user response:

If you want to call your function like this:

ElevatedButton(
    onPressed: () => sayHello(),
    child: const Text("Click"),
)

no you don't need to set async for onPressed, but if you want to call it like this:

ElevatedButton(
    onPressed: () async{
      var result = await sayHello()
    },
    child: const Text("Click"),
)

you need call async, because you need to await for it.

CodePudding user response:

button click

 ElevatedButton(
                    onPressed: () async => sayHello(),
                    child: const Text("Click"),
                  ),

future function:

Future<void> sayHello() async {
   await service.sayHello();
}
  • Related