Junior
What is FutureBuilder in Flutter?
sobes.tech AI
Answer from AI
Widget for building an interface based on asynchronous data received from Future.
Main parameters:
future: An instance ofFutureto observe.initialData: Data displayed before thefuturecompletes.builder: A function (AsyncWidgetBuilder) called on each change of thefuturestate, receivingBuildContextandAsyncSnapshot.
States of AsyncSnapshot:
ConnectionState.none: The Future has not started yet.ConnectionState.waiting: The Future is running.ConnectionState.active: (Rare for Future) The Future has returned intermediate data.ConnectionState.done: The Future has completed (successfully or with an error).
Example usage:
// Suppose we have a function that returns Future<String>
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2)); // Simulate network request
return "Data loaded!";
}
// ... in the build method of a widget:
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: fetchData(), // Our Future
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
// Show a loading indicator while the Future is running
return CircularProgressIndicator();
} else if (snapshot.hasError) {
// Show an error message if the Future completed with an error
return Text('Error: ${snapshot.error}');
} else {
// Show data if the Future completed successfully
return Text('Result: ${snapshot.data}');
}
},
);
}
Advantages:
- Simplifies working with asynchronous operations in UI.
- Automatically rebuilds UI when the
Futurestate changes. - Clearly separates data loading logic from UI building logic.
Disadvantages:
- May lead to unnecessary rebuilds if the
Futureis created inside thebuildmethod. It is recommended to create theFutureonce (e.g., ininitState).