Access the Index on Dart


The following snippet demonstrates how to access the iteration index when using It is a common need in Flutter when looping over or mapping a list of values to widgets.


Unlike JavaScript, one cannot simply access the index of a list during a operation in Dart.

file_type_dartlang main.dart
List myList = ['a', 'b', 'c']; (val, index) {
    // This does not work!
    // Which index am I on?


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.

file_type_dartlang main.dart
myList.asMap() {
    int idx = entry.key;
    String val = entry.value;

    return something;

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]

final List fixedList = Iterable<int>.generate(myList.length).toList(); {
    String val = myList[idx];

    return something;

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.

final List uniqueList = Set.from(myList).toList(); {
    String idx = uniqueList.indexOf(val);

    return something;

Q&A Chat