Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 738
Hasen Avatar asked Sep 16 '25 15:09

Hasen


1 Answers

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.

like image 199
jamesdlin Avatar answered Sep 18 '25 06:09

jamesdlin