Async and Await in Dart
Async and Await in Dart
About
Asynchronous programming is a powerful feature in Dart, allowing you to write code that doesn’t block the execution of other operations while waiting for a time-consuming task to complete. This is particularly important in environments like Flutter, where maintaining a smooth user experience is crucial.
Dart uses Futures to represent values or errors that will be available at some point in the future. The async and await keywords are used to work with Futures, making asynchronous code easier to read and maintain.
How It Works
-
Async: The
asynckeyword is used to mark a function as asynchronous. When you useasync, the function automatically returns aFuture, even if the return type is void. This allows the function to perform asynchronous tasks while keeping the code readable. -
Await: The
awaitkeyword is used inside anasyncfunction to pause its execution until theFuturecompletes. It effectively unwraps theFutureto get its value once it’s ready, without blocking the main thread. -
Future Handling: You can handle the completion of a
Futureusing thethenmethod for success andcatchErrorfor errors. However, usingasyncandawaitprovides a more straightforward way to handle these cases.
Example
Future<String> fetchUserOrder() {
// Simulates a network request that takes 2 seconds to complete.
return Future.delayed(Duration(seconds: 2), () => 'Large Latte');
}
Future<void> main() async {
print('Fetching user order...');
try {
var order = await fetchUserOrder();
print('Order is ready: $order');
} catch (error) {
print('Something went wrong: $error');
}
}Overall
Using async and await in Dart simplifies the handling of Futures by making asynchronous code appear synchronous. This leads to more readable and maintainable code, especially in complex applications. By leveraging these features, Dart developers can efficiently manage tasks like network requests, file I/O, and database queries without blocking the main thread, ensuring that applications remain responsive.