Map through a list with index in Dart
In Javascript, it's easy to map through a list with the value and index. In Dart, you only get the value, but not the index.
One of the top results on Google for this issue is this StackOverflow post from 2 years ago: https://stackoverflow.com/questions/54898767/enumerate-or-map-through-a-list-with-index-and-value-in-dart.
They go through multiple code snippets that implement the functionality. The post also mentions GitHub tickets on the Dart SDK, such as https://github.com/dart-lang/sdk/issues/5245 and https://github.com/dart-lang/sdk/issues/32467. I also stumbled upon this GitHub ticket on the Dart collection package, which proposes to implement enumerate
. This ticket was closed, with a cryptic message saying "Extensions have landed". Still, it doesn't say how to map through a list with index.
By random luck, as I was browsing through the top Flutter packages on pub.dev, I stumbled upon supercharged. This library seems promising, offering a bunch of neat functions. One of them was to do exactly that, with a method called forEachIndexed
. It was annotated with a comment stating "now supported by Dart collection package".
I headed to the collection package, and browsed the API, and sure enough, here it was. https://pub.dev/documentation/collection/latest/collection/IterableExtension.html. They provide an indexed method for map, forEach, fold, etc. It wasn't easy to find, but I'm glad there's an easy, official way to do it in Dart!