Junior — Middle
Could you give an example of using the FutureBuilder widget in your project?
sobes.tech AI
Answer from AI
In one of my projects, I used FutureBuilder for asynchronous data loading from a server and displaying it in the UI. For example, when loading a list of users from an API:
Future<List<User>> fetchUsers() async {
final response = await http.get(Uri.parse('https://api.example.com/users'));
if (response.statusCode == 200) {
return parseUsers(response.body);
} else {
throw Exception('Failed to load users');
}
}
Widget build(BuildContext context) {
return FutureBuilder<List<User>>(
future: fetchUsers(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: \\${snapshot.error}');
} else if (snapshot.hasData) {
return ListView(
children: snapshot.data!.map((user) => ListTile(title: Text(user.name))).toList(),
);
} else {
return Text('No data');
}
},
);
}
This approach allows for convenient management of loading states and displaying the UI based on the result of the asynchronous operation.