What is async and await in Flutter/Dart ?
In Flutter/Dart, async
and await
are used for asynchronous programming, allowing you to write code that performs tasks concurrently without blocking the main thread.
async: This keyword is used to mark a function as asynchronous, It tells Dart that he function will perform an operation that takes time (like fetching data from a server or reading a file) and that will return a Future
object. The Future
represents the value that will be available in the future when the asynchronous operation completes.
Example:
Future<String> fetchData() async {
//Simulate a delay
await Future.delayed(Duration(seconds: 2));
return "Data fetched";
}
await: This keyword can only be used inside and async
function. It is used to pause the execution of the function until the Future
completes and returns a value. Essentially, it waits for the asynchronous operation to finish before proceeding to the next line of code.
Example:
void getData() async {
print("Fetching data...");
String data = await fetchData();
print(data);
}
async
makes a function to return a Future
and allows the use of await
inside.await
pauses the execution of function until the Future
completes and returns the result.
This way, async
and await
make it easier to work with asynchronous operations.