Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
        }
      });
    }
like image 866
GaganSailor Avatar asked Mar 04 '20 11:03

GaganSailor


People also ask

How do you stop a forEach loop in flutter?

To break the forEach loop in dart we use the try-catch clause. Here are the steps to achieve this. Wrap the whole forEach loop inside a try block. On the step, you want to break, throw an exception.

How do you stop a forEach in darts?

You CAN empty return from a forEach to break the loop; List<int> data = [1, 2, 3]; int _valueToBePrinted; data. forEach((value) { if (value == 2) { _valueToBePrinted = value; return; } }); // you can return something here to // return _valueToBePrinted; print(value);

Does Break stop forEach?

break ends execution of the current for , foreach , while , do-while or switch structure.

How do you forEach in darts?

The syntax for forEach loop is smaller and prettier than the for loop. The forEach loop can be used with any type of collection. This loop iterates over each element of the collection and applies the function for each item. The parameter of the function is the type of collection that we are working with.


Video Answer


4 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;
  }
like image 76
Kahou Avatar answered Oct 19 '22 02:10

Kahou


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}"); 
   } 
 } 
}
like image 23
Jiten Basnet Avatar answered Oct 19 '22 03:10

Jiten Basnet


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');
  }
like image 4
Jaydeep chatrola Avatar answered Oct 19 '22 04:10

Jaydeep chatrola


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
}
like image 4
Tanmay Pandharipande Avatar answered Oct 19 '22 03:10

Tanmay Pandharipande