Last active
September 2, 2021 03:38
-
-
Save suragch/dfd2ba694699af6e7f494b5a2f3d2e7e to your computer and use it in GitHub Desktop.
How to create your own 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() { | |
const myString = 'This is a long string that I want to iterate over.'; | |
final myIterable = TextRuns(myString); | |
for (var textRun in myIterable) { | |
print(textRun); | |
} | |
} | |
class TextRuns extends Iterable<String> { | |
TextRuns(this.text); | |
final String text; | |
@override | |
Iterator<String> get iterator => TextRunIterator(text); | |
} | |
class TextRunIterator implements Iterator<String> { | |
TextRunIterator(this.text); | |
final String text; | |
String? _currentTextRun; | |
int _startIndex = 0; | |
int _endIndex = 0; | |
final breakChar = RegExp(' '); | |
@override | |
String get current => _currentTextRun as String; | |
@override | |
bool moveNext() { | |
_startIndex = _endIndex; | |
if (_startIndex == text.length) { | |
_currentTextRun = null; | |
return false; | |
} | |
final next = text.indexOf(breakChar, _startIndex); | |
_endIndex = (next != -1) ? next + 1 : text.length; | |
_currentTextRun = text.substring(_startIndex, _endIndex); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment