skip to Main Content

i am displaying splash screen which waits for 3 seconds and then routes to another screen, but my another screen needs GIF files to load, so i have used precaceh method, so my problem is my splash screen awaits for 3 seconds and then awaits for caching image. i want both to run at the same time and run next line (route) only if both of them is finished (i.e. minimum wait time is 3 seconds, and if images takes more time to caching it should increase wait time).

this is my function which is called in init state

 void delayAndRoute() async {
      await Future.delayed(const Duration(milliseconds: 3000));
      await precacheImage(AssetImage("assets/images/01.gif"), context);
      await precacheImage(AssetImage("assets/images/02.gif"), context);
      await precacheImage(AssetImage("assets/images/03.gif"), context);

      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => const Login(),
        ),
      );
    }

2

Answers


  1. Chosen as BEST ANSWER

    Fully working code

     void delayAndRoute() async {
              // List of futures representing precaching tasks
              List<Future<void>> precacheFutures = [
                Future.delayed(const Duration(milliseconds: 3000)),
                precacheImage(AssetImage("assets/images/01.gif"), context),
                precacheImage(AssetImage("assets/images/02.gif"), context),
                precacheImage(AssetImage("assets/images/03.gif"), context),
              ];
    
          // Waiting for all precaching tasks to complete using Future.wait
          await Future.wait(precacheFutures);
    
          // Navigating to the next screen after all images are precached
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => const Login(),
            ),
          );
        }
    

  2. you can Future.wait method which takes list of futures and Waits for multiple futures to complete and collects their results.
    here is the code:

     Future.wait([
          Future.delayed(const Duration(milliseconds: 3000)),
          precacheImage(const AssetImage("assets/images/01.gif"), context),
          precacheImage(const AssetImage("assets/images/02.gif"), context),
          precacheImage(const AssetImage("assets/images/03.gif"), context),
        ]).then(
          (value) {
             Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => const Login(),
            ),
          );
          },
        );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search