You can use the mapIndexed
or forEachIndexed
extension methods from the collection
package. Note that unlike javascript's array.map()
or C#'s IEnumerable.Select()
, the index is the first argument, not the second argument of the callback:
import 'package:collection/collection.dart';
void main() {
final inputs = ['a', 'b', 'c', 'd', 'e', 'f'];
final indexes = inputs.mapIndexed((index, element) => index).toList();
inputs.forEachIndexed((index, element) {
print('index: $index, element: $element');
});
print(indexes);
}
Old answer
Starting with Dart 2.7, you can use extension
methods to extend the functionalities of Iterable
instead of having to write helper functions:
extension ExtendedIterable<E> on Iterable<E> {
/// Like Iterable<T>.map but the callback has index as second argument
Iterable<T> mapIndexed<T>(T Function(E e, int i) f) {
var i = 0;
return map((e) => f(e, i++));
}
void forEachIndexed(void Function(E e, int i) f) {
var i = 0;
forEach((e) => f(e, i++));
}
}
Usage:
final inputs = ['a', 'b', 'c', 'd', 'e', 'f'];
final results = inputs
.mapIndexed((e, i) => 'item: $e, index: $i')
.toList()
.join('\n');
print(results);
// item: a, index: 0
// item: b, index: 1
// item: c, index: 2
// item: d, index: 3
// item: e, index: 4
// item: f, index: 5
inputs.forEachIndexed((e, i) => print('item: $e, index: $i'));
// item: a, index: 0
// item: b, index: 1
// item: c, index: 2
// item: d, index: 3
// item: e, index: 4
// item: f, index: 5
Map#forEach
? is it what you want?List
? what do you mean? the docs say: "Applies f to each key/value pair of the map. Calling f must not add or remove keys from the map."