flutter precache image code example

Example: flutter precacheimage

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

  Image currentImage;

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

    currentImage = image1;
  }

  
  void didChangeDependencies() {
    super.didChangeDependencies();

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

  
  Widget build(BuildContext context) {
    return Container(
      child: currentImage,
    );
  }

  void setImage(int index) {
      switch (index) {
        case 1: currentImage = image1; break;
        case 2: currentImage = image2; break;
        case 3: currentImage = image3; break;
        case 4: currentImage = image4; break;
      }
  }
}

Tags:

Dart Example