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 Future
s 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 Future
s, making asynchronous code easier to read and maintain.
How It Works#
-
Async: The
async
keyword 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
await
keyword is used inside anasync
function to pause its execution until theFuture
completes. It effectively unwraps theFuture
to get its value once it’s ready, without blocking the main thread. -
Future Handling: You can handle the completion of a
Future
using thethen
method for success andcatchError
for errors. However, usingasync
andawait
provides 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 Future
s 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.