Skip to content

Instantly share code, notes, and snippets.

@NearHuscarl
Forked from devoncarew/main.dart
Last active April 9, 2021 03:00
Show Gist options
  • Save NearHuscarl/86ce74d95798635e14c8b848863b429f to your computer and use it in GitHub Desktop.
Save NearHuscarl/86ce74d95798635e14c8b848863b429f to your computer and use it in GitHub Desktop.
54898767/enumerate-or-map-through-a-list-with-index-and-value-in-dart
// https://gist.github.com/NearHuscarl/86ce74d95798635e14c8b848863b429f
extension ExtendedIterable<E> on Iterable<E> {
/// Like Iterable<T>.map but callback have 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++));
}
}
void main() {
final inputs = ['a', 'b', 'c', 'd', 'e', 'f'];
final results = inputs
.mapIndexed((e, i) => 'item: $e, index: $i')
.toList()
.join('\n');
print('mapIndexed');
print(results);
print('');
print('forEachIndexed');
inputs.forEachIndexed((e, i) => print('item: $e, index: $i'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment