How to stop/break forEach loop in dart /flutter?

Viewed 35707

I want to break the forEach loop after the for loop execution is done.

  void main() {
      var id = [1, 2, 3, 4, 5];


      id.asMap().forEach((index, number) {
        print('ForEach loop');

        for (int i = 0; i < 1; i++) {
          print("for loop");
        }
      });
    }
5 Answers

Can't break forEach with Dart.

You can use for and indexOf

  for (var number in id) {
    var index = id.indexOf(number);

    print('Origin forEach loop');

    for (int i = 0; i < 1; i++) {
      print("for loop");
    }

    break;
  }

I thought this will be helpful for you. using the label to break the loops.

 void main() { 
 outerloop: // This is the label name 

   for (var i = 0; i < 5; i++) { 
   print("Innerloop: ${i}"); 
   innerloop: 

  for (var j = 0; j < 5; j++) { 
     if (j > 3 ) break ; 

     // Quit the innermost loop 
     if (i == 2) break innerloop; 

     // Do the same thing 
     if (i == 4) break outerloop; 

     // Quit the outer loop 
     print("Innerloop: ${j}"); 
   } 
 } 
}

i don't think, you can stop foreach

use for:

var id = [1, 2, 3, 4, 5];

  for (int i in id) {
    if(i == 2)
      break;

    print('$i');
  }

According to your scenario, I think this should work ,

for(int i = 0; i < id.asMap().length; i++){
  if(id.asMap()[i] == 4) //your condition
  {
     break;
  }
  // your for loop
}

Instead of breaking set a boolean to track when to run body of foreach or when not

void main() {
      var id = [1, 2, 3, 4, 5];
      bool forEachDone=false;

      id.asMap().forEach((index, number) {
        //forEachDone=false;
        print('ForEach loop');
       if(!forEachDone){
        for (int i = 0; i < 1; i++,forEachDone=true) {
          print("for loop");
        }

       }
      });
    }
Related