Load your image assets faster in Flutter!
We can have the images in our assets folder, but how to load them faster? Here’s a secret function in Flutter that helps us to do so — precacheImage()
Many times it happens (especially in Flutter Web) that your images from local assets take a lot of time to load and render on your screen!
This is not good for the user’s perspective especially if the image is the background image of your screen. If the image is any component in your screen, we can still show shimmer or something so that the user gets to know that image is loading. But we can’t show shimmer for background image right!
We have a simple yet useful method in Flutter which we can use to load our asset images much faster — precacheImage()!
precacheImage takes ImageProvider and context as required arguments and returns Future<void>
Future<void> precacheImage(
ImageProvider<Object> provider,
BuildContext context,
{Size? size,
ImageErrorListener? onError}
)
This method prefetches the image into the image cache and then whenever the image is used, it will be loaded much faster. However, ImageCache doesn’t allow to hold very large images.
As the context is needed in this, so we can add precacheImage() in any function from where context is accessible. We can put the same in didChangeDependencies() method of your 1st screen!
Example:
void didChangeDependencies() { precacheImage(AssetImage("assets/logo.png"), context); precacheImage(AssetImage("assets/home_bg.png"), context); super.didChangeDependencies();
}
The above example will cache logo.png
and home_bg.png
into the ImageCache. So now, whenever we use this image, it will load faster!
Conclusion
This is a handy tip to load your image assets much faster! Here’s a small stats for how much time does it take to load an image with and without precacheImage()
You can see, the starting 3 print statements are the ones without precacheImage and it took almost 10 milliseconds every time. Now, the next one was with precacheImage and it took 14 milliseconds as it stores the image in the cache. The subsequent loads took only 5 milliseconds. So we can conclude that it reduces the load time to almost 50%! You can find the code on GitHub for the same!
Hope you enjoyed this article!
If you loved it, you can Buy Me A Coffee!
Don’t stop, until you are breathing!💙
- Abhishek Doshi