29

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");
        }
      });
    }
3

6 Answers 6

46

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

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}"); 
   } 
 } 
}
2
  • 2
    I want to break forEach loop not the for loop. Mar 4, 2020 at 11:41
  • @GaganSailor, use for for the usecase you wanted to use... basically does the same thing... idk about performance Nov 15, 2020 at 15:35
5

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');
  }
1
  • Is there any way where we can bypass the ForEach loop?? Mar 4, 2020 at 12:24
4

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

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

       }
      });
    }
2
  • 1
    This will not break the ForEach loop. Mar 4, 2020 at 12:23
  • 1
    you can't break but you can stop execution.
    – Dev
    Mar 5, 2020 at 4:31
1

If you need the index, a more performant method than using indexOf inside a for loop (which increases BigO complexity) would be to use a while loop based on index. Such as:

int index = 0;
while(index < someList.length) {
   if (<some test>) {
     break;
   }
   index++;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.