dart precacheimage code example
Example: flutter precacheimage
class _SampleWidgetState extends State<SamleWidget> {
Image image1;
Image image2;
Image image3;
Image image4;
Image currentImage;
@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");
currentImage = image1;
}
@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: 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;
}
}
}