I've just added an image carousel to my Flutter project using CarouselSlider widget. There's an API that provides the links to the images. I'm using the CachedNetworkImage to get this circular indicator while the image is downloading. The problem is, that after the API call the page is visible, but some images are still loading.
Is there any way to show the images after all of the network images are loaded? In this way, the loading screen will be visible a bit longer but there will be no loading indicator on the images.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Title"),
),
body: Center(
child: _loaded
? CarouselSlider(
options: CarouselOptions(
autoPlay: true,
autoPlayInterval: const Duration(seconds: 5),
autoPlayAnimationDuration:
const Duration(milliseconds: 800),
autoPlayCurve: Curves.bounceInOut,
aspectRatio: 21 / 9),
items: imagePaths.map((i) {
int index = imagePaths.indexOf(i);
return Container(
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.symmetric(horizontal: 5.0),
decoration: BoxDecoration(color: Colors.transparent),
child: CachedNetworkImage(
fit: BoxFit.contain,
placeholder: (context, urlconst) => const Center(
child: SizedBox(
height: 15.0,
width: 15.0,
child: CircularProgressIndicator()),
),
imageUrl: imagePaths[index],
),
);
}).toList(),
)
: const Center(
child: SpinKitFadingCube(
color: Colors.red,
size: 125,
),
),
),
);
}
CodePudding user response:
There is a method in Flutter named precacheImage(imageProvider)
to precache an image using an image provider. The image could be an AssetImage()
or a NetworkImage()
. When you pass the imageProvider inside the precacheImage()
, it will prefetch the image for you.
Documentation: Pre-Cache Image Li
...
@override
void initState() {
super.initState();
image1 = Image.network("https://picsum.photos/200/300");
image2 = Image.asset("https://picsum.photos/200/300");
}
@override
void didChangeDependencies() {
precacheImage(image1.image, context);
precacheImage(image2.image, context);
super.didChangeDependencies();
}
Source: Precache images in flutter
CodePudding user response:
Here is an example of how you can properly precache. Make sure that you override didChangeDependencies
class WidgetWithPrecachedImage extends State<WidgetWithPrecachedImage> {
Image? image1;
@override
void initState() {
super.initState();
image1 = Image.asset('assets/pathtoasset.png');
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
precacheImage(image1!.image, context);
}
@override
Widget build(BuildContext context) {
return Image(image: image1)
),
);
}
}
Here is a live example I made before