A slider feels good when every swipe shows a ready image. If the image starts to load after the swipe, the user sees an empty box first, then the image pops in. The whole slider feels cheap.
The fix is to load images before the user gets to them. Flutter has a function for this, precacheImage. It downloads the image and unpacks it into memory. When the Image widget asks for it later, it's already there.
On every page change, load the two images behind and forward:
PageView.builder( itemCount: images.length, onPageChanged: (index) { // load 2 behind and 2 ahead for (int i = index - 2; i <= index + 2; i++) { // skip the one on screen if (i < 0 || i == index || i >= images.length) continue; precacheImage( NetworkImage(images[i]), context, ); } }, itemBuilder: (context, index) { return Image( image: NetworkImage( images[index], ), ); },)
Why two and not one. onPageChanged fires when the swipe ends. A user who swipes fast can reach the next page before one image is ready. Two images ahead give enough time. And never load all of them: the user may never go till the end, loading twenty images for that is wasted data and wasted memory.
One gap is the first page. onPageChanged fires only when the page changes, so images 2 and 3 need one load at the start:
@overridevoid didChangeDependencies() { super.didChangeDependencies(); // onPageChanged doesn't fire for the first page precacheImage( NetworkImage(images[1]), context, ); precacheImage( NetworkImage(images[2]), context, );}
Not in initState. precacheImage reads screen settings from context, and they are not ready in initState yet.
One more thing. A photo unpacks into memory at its full size, and that's heavy. Use cacheWidth: the image unpacks at the size you show it and takes many times less memory, Load images at the size you show them explains it. In the precache call, it looks like this:
Use the same cacheWidth in the slider and in the precache call. Different sizes are two different images for the cache, and the precached one is never used.
Calling precacheImage on already cached images costs nothing.