Async and Await In Dart

Async And Await In Dart

Both async and await keywords provide a declarative way to define an asynchronous function and use their results. You can use the async keyword before a function body to make it asynchronous. You can use the await keyword to get the completed result of an asynchronous expression.

Important Concept

  • To define an Asynchronous function, add async before the function body.
  • The await keyword work only in the async function.

Example

main() {
print("Start");
getData();
print("End");
}


void getData() async{
  String data = await middleFunction();
  print(data);
}

Future<String> middleFunction(){
  return Future.delayed(Duration(seconds:5), ()=> "Hello");
}

Show Output
In the above example, async handles the states of the program where any part of the program can be executed. async always comes with await because await holds the part of the program until the rest of the program executed.

Handling Errors

You can handle errors in the dart async function by using try-catch. You can write try-catch code the same way you write synchronous code.

Example

main() {
print("Start");
getData();
print("End");
}


void getData() async{
    try{
         String data = await middleFunction();
  print(data);
    }catch(err){
        print("Some error $err");
    }
 
}

Future<String> middleFunction(){
  return Future.delayed(Duration(seconds:5), ()=> "Hello");
}

Show Output
In the above example, try-catch handles the exception that could come after the program is executed.

Info

Note: We cannot perform an asynchronous operation from a synchronous function.