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");
}
});
}
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.
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);
break ends execution of the current for , foreach , while , do-while or switch structure.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With