Reputation: 875
I get different imageURLs from Firestore multiple times and display them on the screen, but it feels a little slow to load. So I want to preaload the image, is there a way?
Specifically, in the following code, when counter == 0, I want to read the imageURL when counter == 1, 2. (Flutter will then cache the image, so when the counter reaches 1 or 2, the image will load faster.)
I also tried CachedImageNetwork but didn't know how to adapt it to this case
class TestScreen extends StatefulWidget {
@override
_TestScreenState createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
int counter=0;
List imageURLList=['url1','url2','url3'];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.network(imageURLList[counter]),
RaisedButton(
onPressed: (){
setState(() {
counter++;
});
},
child: Text('push'),
),
],
),
),
);
}
}
Upvotes: 1
Views: 861
Reputation: 7328
If I understand correctly, you want to load your network image even when they are not displayed.
EDIT after testing: Instead of using a List of url I would use a List containing NetworkImage object and using the method precacheImage
.
class _TestScreenState extends State<TestScreen> {
int counter = 0;
List<NetworkImage> imgList = [
NetworkImage("url1"),
NetworkImage("url2"),
NetworkImage("url3"),
];
@override
void didChangeDependencies() {
super.didChangeDependencies();
for (var img in imgList) {
precacheImage(img, context);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image(image: imgList[counter]),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
counter++;
});
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Upvotes: 1