Skip to content

Instantly share code, notes, and snippets.

@ianjsikes
Created May 27, 2018 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianjsikes/625e95a28378b77af51f43880b408139 to your computer and use it in GitHub Desktop.
Save ianjsikes/625e95a28378b77af51f43880b408139 to your computer and use it in GitHub Desktop.
Dart utility method to map over a list, getting the value __and__ index.
typedef B MapWithIndexCallback<B, A>(A a, int index);
Iterable<B> mapWithIndex<B, A>(List<A> l, MapWithIndexCallback<B, A> cb) {
Map<int, A> map = l.asMap();
return map.keys.map((key) {
return cb(map[key], key);
});
}
// Example usage
List<Widget> exampleList() {
return mapWithIndex(['A', 'B', 'C'], (item, index) {
return Text("Item ${item} is at index ${index}");
}).toList()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment