How can I break from dart generator based on some condition?
fn sync*(...){
yield 1;
yield 2;
if(someCondition()) //cancel/break the generator
yield 3;
if(someCondition2()) //cancel/break the generator
yield 4;
if(someCondition4()) //cancel/break the generator
yield 5;
}
CodePudding user response:
Simply return
from your generator when you want it to stop generating new values:
Iterable<int> fn(bool flag) sync* {
yield 1;
yield 2;
if (flag) {
return;
}
yield 3;
}
void main() {
print(fn(true).toList()); // Prints: [1, 2]
print(fn(false).toList()); // Prints: [1, 2, 3]
}