Reputation: 39
In my app I have an InkWell on an image that I want to turn into a different image when you click on it. I have set up a list where the onTap simply cycles through the list onto the next image. The problem is, when you click it, it takes about half a second for the next image to load. I would like to be able to show the images instantaneously when clicking it.
int index = 0;
@override
Widget build(BuildContext context) {
List images = [
Image.asset('assets/image0.jpg'),
Image.asset('assets/image1.jpg'),
Image.asset('assets/image2.jpg'),
Image.asset('assets/image3.jpg'),
];
return InkWell(
onTap: () {
setState(() {
index++;
});
},
child: images[index],
);
}
This is my current code
Upvotes: 1
Views: 199
Reputation: 20008
it takes about half a second for the next image to load
This is probably because your List
of images
is within your build
method, so every setState
it rebuilds.
Move your List outside of the build
method:
int index = 0;
List images = [
Image.asset('assets/image0.jpg'),
Image.asset('assets/image1.jpg'),
Image.asset('assets/image2.jpg'),
Image.asset('assets/image3.jpg'),
];
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
setState(() {
index++;
});
},
child: images[index],
);
}
Upvotes: 3