I have built a FutureBuilder to check Futures then redirect based on that, but as it's a FutureBuilder, I have to return the Screen NOT ROUTING to them . Can somebody share an example of how to listen for a bunch of futures without a FutureBuilder , so I can Route with animation instead of dummy return.
FutureBuilder(
future: Future.wait([
firstFuture(),
secondFuture(),
]),
builder: (
context,
AsyncSnapshot<List<bool>> snapshot,
){
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
// If all future passed return home.
if (snapshot.data[0] && snapshot.data[1])
// Instead I want: MaterialPageRoute(builder: (_) => HomeScreen());
return HomeScreen();
// Instead I want: MaterialPageRoute(builder: (_) => permissionsScreen());
return permissionsScreen();
}
);
Based on pskink's advice, I implemented this code which will loop and wait for a bunch of Futures to finish, then route or whatever without a FutureBuilder:
//.. inside a StatfulWidget or whatever...
// Loop thru Dependencies List(Futures) and make sure all are loaded(finished).
Future<bool> loadDependencies(List<Future<bool>> dependenciesList) async {
bool isAllDone = true;
// Load dependencies.
for (Future<bool> dependency in dependenciesList) {
bool currentDep = await dependency;
isAllDone = isAllDone && currentDep;
if (!isAllDone) return false; // Break if any failed.
}
return isAllDone;
}
Then call it, here's an example:
//.. inside a StatfulWidget
// Define App's Dependencies List.
final List<Future<bool>> dependenciesList = [
someBloc.fetchData(),
];
@override
void initState() {
super.initState();
// Load dependencies then route once done.
loadDependenciesAndRoute();
}
void loadDependenciesAndRoute() async {
bool loadingStatus = await loadDependencies(dependenciesList);
if (loadingStatus) {
// As Context is not ready inside initState, routing using navigatorKey.
await AppKeys.navigatorKey.currentState.push(
Routes.home(),
);
} else {
await AppKeys.navigatorKey.currentState.push(
Routes.onLoading(),
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.