Flutter: Efficiently loading images between animations

I was recently playing with Flutter’s PaletteGenerator library. The library does what Android’s Palette API does: gives you a palette of colors based on a bitmap given.

The experience I was going for was to use the dominant color from an image to color the detail screen when the user tapped on it.

It’s fairly easy to use the library if you have a handle on the ImageProvider or the Image object.

getDominantColor(ui.Image img, Function(PaletteColor) onColor){
  if(img == null) onColor(null);
  PaletteGenerator.fromImage(img).then((PaletteGenerator g){

Most of the examples I have seen for PaletteGenerator use an in-app image that the system can immediately load but using remote images is more complicated since the library has to wait for enough of the image to load to read the color data. This gets further complicated if you need to run an animation while loading the image.

After trying a number of iterations, the best approach seems to be using Flutter’s precacheImage method before kicking off the animation

await precacheImage(NetworkImage(b.image), context);

Also, consider using the CacheImage library to improve later performance if that screen is loaded multiple times