Home > Software design >  Is it possible to iterate a list with index values in the Widget tree?
Is it possible to iterate a list with index values in the Widget tree?

Time:04-21

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?

CodePudding user response:

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)
  ],
)
  • Related