'Flutter iterate through List with access to index

I tried some other solutions to this like using asMap() and forEach but kept getting different errors. Like it was saying the return type of my ChartBar isn't a 'MapEntry', as defined by anonymous closure, or The expression here has a type of 'void', and therefore cannot be used.

Row(
    mainAxisSize: MainAxisSize.min,
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    crossAxisAlignment: CrossAxisAlignment.end,
    children: myList.map((data) {
      return ChartBar(
          ///etc
    }).toList(),
  )

I want the index as well.



Solution 1:[1]

mirkancal's suggestion didn't work because Map.map returns another Map (and therefore the enumeration callback you pass it is expected to return a MapEntry).

You instead need to use Map.entries so that you can use Iterable.map instead to construct a List:

Row(
    mainAxisSize: MainAxisSize.min,
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    crossAxisAlignment: CrossAxisAlignment.end,
    children: myList.asMap().entries.map((MapEntry entry) {
      return ChartBar(entry.key, entry.value);
    }),
  )

You alternatively can use Dart's new collection-for construct:

Row(
    mainAxisSize: MainAxisSize.min,
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    crossAxisAlignment: CrossAxisAlignment.end,
    children: [for (MapEntry entry in myList.asMap().entries)
      ChartBar(entry.key, entry.value)
    ],
  )

In the above, entry.key will be the index, and entry.value will be the original value in myList.

Solution 2:[2]

For the index you could use indexOf(value) function from the list to get index value. For example:

List list = List.generate(3, (int index) => index * index); // [0, 1, 4]

list.indexOf(4) // returns 2

As for your other issue, I'd need to see more code to see how you populate myList. I would suggest this approach (if it fits) to render your Row children. Use a function to return that list, for example:

buildList() {
 List<Widget> list = List<Widget>();

 chartBars.forEach((chart) => { //chartBars list with info
  // add your ChartBar widget to the list with appropiate info
  list.add(ChartBar(someProperty: chart.property));
 });
 return list;
}

Then on your Row widget just call that function when you build it's children:

Row(
    mainAxisSize: MainAxisSize.min,
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    crossAxisAlignment: CrossAxisAlignment.end,
    children: buildList()      
)

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
Solution 2 Rodolfo Franco