flutterdart

Await the loading of background Image in Container


I have an issue with how long it takes to load a backgroundImage in a controller. I am using a Container's backgroundImage property as a background for my Scaffold. But during the loading of that particular page, it shows a black background until the image is loaded.

Is there a way I can wait for the image to be loaded before I navigate to the said page?

Below is my Code sample of the page in question:

Widget build(BuildContext context) {
return Container(
  decoration: BoxDecoration(
    image: DecorationImage(
      image: AssetImage(imgSubscriptionBGPNG),
      fit: BoxFit.fitHeight,
    ),
  ),
  child: Scaffold(
    backgroundColor: Colors.transparent,
    body: Column()
  ),
);

Solution

  • Thanks to @Mr Random for the suggestion.

    I did precache the image on the previous screen and passed it as an argument to the next page. That worked for me.

    Here are the code snippets:

    In the State class of the first screen:

    final bgImage = AssetImage(imgSubscriptionBGPNG);
    @override
    void didChangeDependencies() {
      precacheImage(bgImage, context);
      super.didChangeDependencies();
    }
    

    And in the build function:

    BtnButton(
     onPressed: () {
      Navigator.push(context,CupertinoPageRoute(
                builder: (context) 
                   => SubscriptionScreen(bgImage: bgImage)));}),