Skip to content

Instantly share code, notes, and snippets.

@WahdanZ
Last active June 24, 2020 22:55
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 WahdanZ/7cd0df2fe1e4476a11d6085801ea0114 to your computer and use it in GitHub Desktop.
Save WahdanZ/7cd0df2fe1e4476a11d6085801ea0114 to your computer and use it in GitHub Desktop.
Extension Iterable
void main() {
final list = ['a', 'b', 'c'];
list.mapIndex((i, index) {
print("item $i inddex $index ");
}).toList();
print("===============");
list.forEachIndex((i, index) {
print("item $i inddex $index ");
});
print(list.getOrElse(7,()=>"7"));
}
extension ExtensionIterable<E> on Iterable<E> {
Iterable<T> mapIndex<T>(T f(E e, int i)) {
var i = 0;
return this.map((e) => f(e, i++));
}
void forEachIndex(void f(E e, int i)) {
var i = 0;
this.forEach((e) => f(e, i++));
}
E getOrNull(int index) {
try {
return this.elementAt(index);
} catch (e) {
return null;
}
}
E getOrElse(int index, E f()) {
try {
return this.elementAt(index);
} catch (e) {
return f();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment