In Dart, async and await are keywords used to handle asynchronous operations, which are tasks that take time to complete, like fetching data from a server, reading a file, or querying a database. They allow your program to wait for a task to complete without blocking the rest of the code, making it more efficient and responsive.
async:
You mark a function asasyncwhen it performs asynchronous operations. This tells Dart that the function will return a Future, which represents a value that will be available later.
Future fetchData() async {
// Simulate network delay
await Future.delayed(Duration(seconds: 2));
return "Data loaded";
}
await:
Inside an async function, you use await before a Future to pause execution until the Future completes. This makes asynchronous code easier to read, almost like synchronous code.
void main() async {
print("Fetching data...");
String data = await fetchData();
print(data); // Output after 2 seconds: Data loaded
}
- Practical Example:
I’ve usedasyncandawaitwhen building apps that fetch user profiles from APIs. Instead of blocking the UI while waiting for a network call, the app remains responsive, showing loading indicators until the data is ready. - Challenges:
- Forgetting to use
awaitcan cause code to execute before the asynchronous task completes. - Exception handling requires care; you should use
try-catchblocks to handle errors in async functions.
try {
String data = await fetchData();
} catch (e) {
print("Error occurred: $e");
}
Alternative:
Before async/await, Dart used then() with Futures:
fetchData().then((data) {
print(data);
});
While this works, async/await makes the code much cleaner and easier to maintain, especially for multiple sequential asynchronous operations.
