Last active
June 24, 2020 22:55
-
-
Save WahdanZ/7cd0df2fe1e4476a11d6085801ea0114 to your computer and use it in GitHub Desktop.
Extension Iterable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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