Member-only story
Flutter Image Caching Anti-Patterns

There are some image caching from the asset bundle antipatterns floating around. In this article, I am going to show how a knowledge of Flutter internals including widget lifecycles can be used to implement image caching from the asset bundle correctly.
The Image Caching Anti-Pattern
So first, let me show the most common repeated image caching from asset bundle solution and explain why it does not work from how the flutter framework really works.
Here is the antipattern that one usually finds in answers to stackoverflow questions:
What is wrong here? Well, the flutter stateful widget lifecycle is structured in such a way that didChangeDependencies is executed after the first build of the widget so despite the name of the function precacheImages it is in fact not precaching or even caching images in the right place in the app lifecycle.
What we want is to say upon the first frame being rendered by the Flutter Engine our caching logic gets executed to load the images in the asset bundle into memory so that when we next use the asset image path strings to load an image it results in the Flutter Engine accessing those images from memory rather than re-load it from the asset bundle.
There is a mixin that acts as glue between the render tree and the Flutter Engine that we will use, it’s in the render package at:
WidgetsFlutterBinding.ensureInitialized calls the class RendingFlutterBinding class which then calls the RendererBinding mixin. Which then means that after the WidgetsFlutterBinding.ensureInitialized we get access to the RendererBinding methods such as:
deferFirstFrame