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) return;
  PaletteGenerator.fromImage(img).then((PaletteGenerator g){
    onColor(g.dominantColor);
  });
}

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

Author: Arpit Mathur

Arpit Mathur is a Principal Engineer at Comcast Labs where he is currently working on a variety of topics including Machine Learning, Affective Computing, and Blockchain applications. Arpit has also worked extensively on Android and iOS applications, Virtual Reality apps as well as with web technologies like JavaScript, HTML and Ruby on Rails. He also spent a couple of years in the User Experience team as a Creative Technologist.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: