By default, FutureBuilder provides a single future
parameter that handles a single Future. For multiple Futures, we can combine them into a single Future
using Future.wait
. Here’s a step-by-step guide on how to do this:
Create a list of Future
objects
Create a list of Future
objects that represent the asynchronous operations you want to perform. For example, let’s assume you have two futures:
Future<String> fetchFirstData() async {
// Simulate a network request or other asynchronous operation.
await Future.delayed(Duration(seconds: 2));
return "First Data";
}
Future<int> fetchSecondData() async {
// Simulate another asynchronous operation.
await Future.delayed(Duration(seconds: 3));
return 42;
}
Combine the futures using Future.wait
Use the Future.wait
method to combine the individual futures into a single future. Future.wait
takes a list of futures as an argument and returns a single future that completes when all the input futures have completed.
Future<void> fetchData() async {
await Future.wait([fetchFirstData(), fetchSecondData()]);
}
Create a FutureBuilder
widget
Now, use the FutureBuilder
widget to handle the combined future and display the results in your widget tree. You can place this widget in your build
method.
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// Use the results from the futures here.
if (snapshot.hasError) {
return Text("Error: ${snapshot.error}");
} else {
return Column(
children: [
Text("First Data: ${snapshot.data[0]}"),
Text("Second Data: ${snapshot.data[1]}"),
],
);
}
} else {
// While waiting for the futures to complete, you can show a loading indicator or placeholder.
return CircularProgressIndicator();
}
},
);
}
}
In the code above, we use the snapshot
to check the connectionState
. When the connectionState
is ConnectionState.done
, it means that both futures have completed. You can access the results using snapshot.data
.
Remember to replace the fetchFirstData
and fetchSecondData
functions with your actual asynchronous operations. This example demonstrates how to use FutureBuilder
to handle multiple futures in a single widget in Flutter.
Foto von Tomasz Frankowski auf Unsplash
Leave a Reply