Flutter image preload

Use the precacheImage function to start loading an image before your drawer is built. For example, in the widget that contains your drawer:

class MyWidgetState extends State<MyWidget> {

  @override
  void initState() {
    // Adjust the provider based on the image type
    precacheImage(new AssetImage('...'));
    super.initState();
  }

}

I had problems with the upper solution which uses precacheImage() inside initState. The code below resolved them. Also note that you might not see expected results in the debug mode but only in the release mode.

Image myImage;

  @override
  void initState() {
    super.initState();
    myImage= Image.asset(path);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    precacheImage(myImage.image, context);
  }

There is a good article on this subject : https://alex.domenici.net/archive/preload-images-in-a-stateful-widget-on-flutter

It should look something like this

class _SampleWidgetState extends State<SampleWidget> {
  Image image1;
  Image image2;
  Image image3;
  Image image4;

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

  @override
  Widget build(BuildContext context) {
    return Container(
          child: Stack(
            children: <Widget>[
              image1,
              image2,
              image3,
              image4,
            ],
          ),
        );
  }
}

Tags:

Dart

Flutter