I want to call a loading screen widget that has a column with an image, a text and a loading indicator, 5 seconds after the screen is built there should called a setState-method that changes a boolean value[foundOpponent] and with that the screen (the text should be changed into "found opponent" and the indicator into an Icon) after that there should be a delay of 2 seconds and then a Navigator.push to another screen.
I have already looked at https://stackoverflow.com/questions/49466556/flutter-run-method-on-widget-build-complete and tried most of the explained methods and it somewhat worked but the screen of the virtual phone was extremely lagging , the image that should get built in the build method does not even get displayed and while the image is loading the method that should get called after the build is being executed.
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
sleep(const Duration(seconds: 10));
setState(() {
foundOpponent = true;
});
sleep(const Duration(milliseconds: 2500));
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const QuestionMainPage()),
);
});
}
I've tried the following methods:
WidgetsBinding.instance
.addPostFrameCallback((_) => yourFunction(context));
SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));
}
Future<void> _runsAfterBuild() async {
await Future((){}); // <-- Dummy await
// This code runs after build
}
@override
Widget build(BuildContext context) {
_runsAfterBuild();
return Container();
}
CodePudding user response:
Try using Future.delayed
and make sure to put await
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
await Future.delayed(Duration(seconds: 10));
//await task a
await Future.delayed(Duration(seconds: 1));
//await task B
});
}