dartflutter

Enumerate or map through a list with index and value in Dart


In dart there any equivalent to the common:

enumerate(List) -> Iterator((index, value) => f)
or 
List.enumerate()  -> Iterator((index, value) => f)
or 
List.map() -> Iterator((index, value) => f)

It seems that this is the easiest way but it still seems strange that this functionality wouldn't exist.

Iterable<int>.generate(list.length).forEach( (index) => {
  newList.add(list[index], index)
});

Solution

  • There is an asMap method which converts the List to a Map where the keys are the indices and the values are the elements. Please take a look at the documentation for asMap.

    Example:

    final sample = ['a', 'b', 'c'];
    sample.asMap().forEach((index, value) => f(index, value));
    

    If you are using Dart 3, you can alternatively use the indexed property. Please take a look at the documentation for indexed.

    Example:

    final sample = ['a', 'b', 'c'];
    for (final (index, item) in sample.indexed) {
      f(index, item);
    }