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 async keyword is used to mark a function as asynchronous. When you use async, the function automatically returns a Future, 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 an async function to pause its execution until the Future completes. It effectively unwraps the Future to get its value once it’s ready, without blocking the main thread.

  • Future Handling: You can handle the completion of a Future using the then method for success and catchError for errors. However, using async and await 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 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.