DEV Community

Pere Sola
Pere Sola

Posted on

How to access index of an array while mapping in Flutter

If you come from Javascript, like me, you were probably expecting that when mapping over an array you had access to the index of the item, like so:

myArray.map((item, index) => {
     // whatever
}
Enter fullscreen mode Exit fullscreen mode

Well, the index in Dart is not available. So you will first have to convert the array to a map, with key-value pairs, like so:

myArray.asMap().entries.map((entry) {
    int idx = entry.key; // this is the index
    String val = entry.value;

    return whatever;
}
Enter fullscreen mode Exit fullscreen mode

Don't forget to call asMap, like so: asMap(), and chain entries. If you need the outcome to be a Flutter List, you need to add the toList() at the end.

Kudos to these folks for teaching me this. Dart docs here.

Top comments (0)