'Is it possible to iterate a list with index values in the Widget tree?
I have a List which is a list of image URLs, which I will then use to construct a series of Image widgets as part of a gallery. The images will be aligned next to each other in a Wrap.
I can iterate the list and build my images inside a wrap just fine, but I also need to identify the image index in the List and pass it to my image widget
var gallery = ['image1.jpg','image2.jpg','image3.jpg']; // this is sample data, my real data set is much longer and obtained from JSON data
Wrap(
spacing: 2,
runSpacing: 2,
children: [
for (var image in gallery)
ImageItem(image: image, index:index) <--- how can I get the index here?
],
)
Is it possible to identify the index, or where the image is in my list?
Solution 1:[1]
You can do:
var gallery = ['image1.jpg','image2.jpg','image3.jpg']; // this is sample data, my real data set is much longer and obtained from JSON data
Wrap(
spacing: 2,
runSpacing: 2,
children: [
for (var i = 0; i < gallery.length; i++)
ImageItem(image: gallery[i], index: i)
],
)
Solution 2:[2]
Another way is to use the mapIndexed method from the Flutter built-in collection package, so your code would be:
import 'package:collection/collection.dart'; // Importing the collection package
var gallery = ['image1.jpg','image2.jpg','image3.jpg']; // this is sample data, my real data set is much longer and obtained from JSON data
Wrap(
spacing: 2,
runSpacing: 2,
children: gallery.mapIndexed((index,image) => ImageItem(image: image, index: index)).toList(),
)
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 | Rémi Rousselet |
| Solution 2 | Moaz El-sawaf |
