flutterasynchronousfuture

Invoke async method on button click Flutter


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?


Solution

  • 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.