Async/await and Futures help your app wait for tasks that take time, like loading data, without freezing the screen.
Async/await and Futures in Flutter
Future<Type> functionName() async {
// code that waits for something
var result = await someAsyncCall();
return result;
}Future means a value that will be ready later.
async marks a function that can wait for Futures.
Future<String> fetchUserName() async { return 'Alice'; }
Future<int> waitAndReturn() async { await Future.delayed(Duration(seconds: 2)); return 42; }
Future<void> printUserName() async { String name = await fetchUserName(); print(name); }
This Flutter app shows a loading spinner for 2 seconds, then displays a greeting message. It uses async/await to wait for the greeting.
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); Future<String> fetchGreeting() async { await Future.delayed(const Duration(seconds: 2)); return 'Hello from Future!'; } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Async/Await Example')), body: Center( child: FutureBuilder<String>( future: fetchGreeting(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } else if (snapshot.hasError) { return const Text('Error occurred'); } else { return Text(snapshot.data ?? 'No data'); } }, ), ), ), ); } }
Use async on functions that return a Future and use await to pause until the Future finishes.
Never block the main UI thread; async/await helps keep the app smooth and responsive.
Use FutureBuilder widget in Flutter to show UI based on Future state.
Async/await lets your app wait for slow tasks without freezing.
A Future is a value that will be ready later.
Use FutureBuilder to update UI when a Future completes.
Practice
What does the async keyword do in a Flutter function?
Solution
Step 1: Understand the role of
Theasyncasynckeyword marks a function so it can pause execution until a Future finishes.Step 2: Connect
Inside anasyncwithawaitasyncfunction, you can useawaitto wait for a Future without blocking the app.Final Answer:
It allows the function to useawaitto pause until a Future completes. -> Option BQuick Check:
asyncenablesawaitusage [OK]
- Thinking async runs code faster by multithreading
- Confusing async with UI widgets
- Assuming async retries failed calls automatically
Which of the following is the correct way to declare a function that returns a Future of type int?
?Solution
Step 1: Check return type and async keyword
The function must return a Future<int> and be marked async to use await or return a Future.Step 2: Validate syntax correctness
Future<int> fetchNumber() async { return 42; } correctly declares the return type and uses async before the function body.Final Answer:
Future<int> fetchNumber() async { return 42; } -> Option AQuick Check:
Correct Future return type with async [OK]
- Placing async before Future in declaration
- Missing Future return type
- Returning int directly without Future
What will be printed by this Flutter code?
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return 'Done';
}
void main() async {
print('Start');
var result = await fetchData();
print(result);
print('End');
}Solution
Step 1: Trace the print statements and await
First, 'Start' prints immediately. Thenawait fetchData()pauses main until fetchData completes after 1 second.Step 2: After fetchData returns, print result and 'End'
Once fetchData returns 'Done', it prints 'Done' then prints 'End'.Final Answer:
Start\nDone\nEnd -> Option AQuick Check:
Await pauses main, so prints in order [OK]
- Assuming 'Done' prints before 'Start'
- Ignoring await delay effect
- Thinking 'End' prints before 'Done'
Identify the error in this Flutter async code snippet:
Future<void> loadData() async {
var data = fetchData();
print(data);
}
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return 'Data loaded';
}Solution
Step 1: Check how fetchData() is called
fetchData() returns a Future<String>, but loadData() does not await it, so data is a Future, not the string.Step 2: Understand print output
Printing data prints the Future object, not the resolved string. Adding await fixes this.Final Answer:
Missing await before fetchData() causing print to show Future instance. -> Option CQuick Check:
Await needed to get Future result [OK]
- Forgetting to await async calls
- Thinking print can't be used in async
- Misreading Duration syntax
You want to fetch user data and then fetch user posts only after the user data is ready. Which code correctly uses async/await to do this?
Future<String> fetchUser() async {
await Future.delayed(Duration(seconds: 1));
return 'User123';
}
Future fetchPosts(String user) async {
await Future.delayed(Duration(seconds: 1));
return ['Post1', 'Post2'];
}
void main() async {
// Fill in the blanks
var user = ?;
var posts = ?;
print('User: $user');
print('Posts: $posts');
}Solution
Step 1: Await fetchUser() to get user before fetching posts
We must wait for fetchUser() to complete to get the user string before calling fetchPosts.Step 2: Await fetchPosts(user) to get posts list
Since fetchPosts returns a Future, we await it to get the actual list before printing.Final Answer:
var user = await fetchUser();\nvar posts = await fetchPosts(user); -> Option DQuick Check:
Await both calls in sequence for correct data [OK]
- Not awaiting fetchUser before fetchPosts
- Not awaiting fetchPosts result
- Trying to await non-Future values
Ready to prove it?
Pass the test and this pattern moves unknown
