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…