0

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();
}
808code
  • 17
  • 4

1 Answers1

0

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
    });
  }

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • It worked, thanks a lot, is there maybe a way to minimize the loading time of the LoadingScreen, because right now it takes about 4 seconds to load the widget? – 808code Oct 27 '22 at 15:42
  • Sorry cant tell. If you are talking about splash screen, it takes some time(web specially) based on code & device's config. try to check the logic. If you fail, you can create a question with [minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example) – Md. Yeasin Sheikh Oct 27 '22 at 15:50