Dart Futures & Async/Await

Understanding how Dart handles tasks that take time — like waiting for data.

1. What are Futures and Async/Await? (Programming Definition)

In programming, sometimes you ask your computer to do something that takes time, like fetching data from the internet. A Future is a special object that represents a task that will finish later — it promises to give you a result once it's done.

async and await are keywords that help you write code that waits for these Futures to finish, but without freezing your whole program.

2. Real-World Example: Futures & Async/Await

Imagine you order a pizza (the task). The pizza shop promises to deliver it in 30 minutes (that's the Future). You don't want to just stand there waiting — you want to do other things like chatting with friends. Later, when the pizza arrives, you get it and eat.

async/await helps you tell your program, "Hey, wait here for the pizza but don't stop everything else."

3. Important Keywords in Dart Futures & Async/Await

4. Example of Using Futures with async & await in Dart

Future fetchUserOrder() {
  // Imagine this function is fetching data from the internet and it takes 3 seconds
  return Future.delayed(Duration(seconds: 3), () => 'Pizza is ready!');
}

void main() async {
  print('Order placed...');
  
  // Wait here for the pizza to be ready, but the program won't freeze!
  String order = await fetchUserOrder();
  
  print(order);
  print('Enjoy your meal!');
}

Explanation:

5. Why Use Futures & Async/Await?

Without Futures and async/await, your app would freeze or stop while waiting for things like:

Using these concepts helps your app stay smooth and responsive, making users happy.

6. Summary