Component - Async/await and Futures
This Flutter component demonstrates how to use async/await with Futures to fetch data asynchronously. It shows a button that, when pressed, starts loading data and then displays the result once ready.
This Flutter component demonstrates how to use async/await with Futures to fetch data asynchronously. It shows a button that, when pressed, starts loading data and then displays the result once ready.
Scaffold
├─ AppBar
│ └─ Text
└─ Center
└─ Column
├─ ElevatedButton
└─ Padding
└─ TextWhat does the async keyword do in a Flutter function?
asyncasync keyword marks a function so it can pause execution until a Future finishes.async with awaitasync function, you can use await to wait for a Future without blocking the app.await to pause until a Future completes. -> Option Basync enables await usage [OK]Which of the following is the correct way to declare a function that returns a Future of type int?
?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');
}await fetchData() pauses main until fetchData completes after 1 second.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';
}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');
}Pass the test and this pattern moves unknown