Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to break from middle of generator in dart?

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading