Understanding how Dart handles tasks that take time — like waiting for data.
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.
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."
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:
fetchUserOrder() returns a Future that completes after 3 seconds with a string.main() is marked async because it uses await to wait for the Future.
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.