'Preload network images to avoid load times

I'd like to add and remove items on top of each on the press of a button to avoid load times for network images. My idea is to add ~5 images to a Stack on top of each other and be able to remove the top one and add another on to the back so that it can pre-load.

I did not find any documentation or answers if this is possible with the Stack class

I also had the idea to use a Dismissible, but there seems to be no way to change child and background on it either.



Solution 1:[1]

You shouldn't have to create a stack to preload images; what you're looking for is the NetworkImage class. You could maintain a set of NetworkImage classes that you've manually loaded and pass one of those into the Image constructor, but I'm fairly sure that flutter actually caches the last few images you've loaded in memory automatically so that isn't even really needed (I think I heard the last 100 images or so but I could be wrong).

Unfortunately, the API isn't all that simple for it (there's a bug open about this in the flutter repo), but it's not all that difficult either.

All you need is a method somewhere like this (or just do it in a build function):

static void preload(BuildContext, String path) {
  final configuration = createLocalImageConfiguration(context);
  NetworkImage(path).resolve(configuration);
}

Call that from anywhere you have a valid build context. And TBH, you could construct the ImageConfiguration yourself and pass that in instead (just look at the source for createLocalImageConfiguration to get an idea about that).

If you want to get a bit fancier about it, instead of just making an NetworkImage and resolving it, you could have a class that maintains a map of preloaded NetworkImages and returns them when you want.

Another thing you can do which might be enough to resolve your problem without doing anything else is setting gaplessPlayback = true where you construct your Image.network - that will make sure that the image doesn't switch until the next image is fully loaded.

Hope that helps =). If it doesn't actually work let me know though and I'll dig a bit deeper - I haven't done it in code myself yet.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1