The following snippet demonstrates how to access the iteration index when using List.map. It is a common need in Flutter when looping over or mapping a list of values to widgets.
Problem
Unlike JavaScript, one cannot simply access the index of a list during a List.map operation in Dart.
Solutions
There are several ways to access the index when looping over a List.
Use Map Entries
Convert the List to a Map, then map the entries containing the key/value pairs. Each key in the map is the index of the original list.
Generate a Fixed Range List
If you are looping over many lists that have a fixed length, it may be more efficient to generate a single list once. For example, the we create a ranged list that is the same length as the original, i.e. [0, 1, 2, ..., n]
Grab the Index of Unique Values
You can access the index of a specific value by searching for it with List.indexOf, which returns the index of the first match. This approach is most predictable when all values are unique. A Set can ensure uniqueness throughout the list.