Preloading image in flutter clarification

Viewed 176

I know this question was asked here before: Flutter image preload

Based on this article: https://alex.domenici.net/archive/preload-images-in-a-stateful-widget-on-flutter

I know that you can preload image using this code:

@override
  void initState() {
    super.initState();

    image1 = Image.asset("assets/image1.png");
    image2 = Image.asset("assets/image2.png");
    image3 = Image.asset("assets/image3.png");
    image4 = Image.asset("assets/image4.png");
}

@override
void didChangeDependencies() {
  super.didChangeDependencies();

  precacheImage(image1.image, context);
  precacheImage(image2.image, context);
  precacheImage(image3.image, context);
  precacheImage(image4.image, context);
}

My question now is why do we need to load the image under initState method? The codes under didChangeDependencies alone is enough to preload the image right? Like this:

@override
void didChangeDependencies() {
  super.didChangeDependencies();

  precacheImage("assets/image1.png", context);
  precacheImage("assets/image2.png", context);
  precacheImage("assets/image3.png", context);
  precacheImage("assets/image4.png", context);
}
1 Answers

Loading image under the initState is just setting up the instances image1,...,image4

As the precacheImage requires the context (as function argument) to process, that has been moved to didChangeDependencies.

Of course, you can move the code from initState to didChangeDependencies, but as said before it may invoke the code more than once, the necessary set of lines kept in didChangeDependencies to access the context.

Related