Suragch
Suragch

Reputation: 512316

How to break out of nested loops in Dart

Given the following nested loop:

for (int i = 0; i < 10; i++) {
  for (var j = 0; j < 10; j++) {
    print('i: $i, j: $j');
  }
}

If I add a break statement to the inner loop:

for (int i = 0; i < 10; i++) {
  for (var j = 0; j < 10; j++) {
    print('i: $i, j: $j');
    break; //                      <-- break
  }
}

It only breaks out of the inner loop. This is the output:

i: 0, j: 0
i: 1, j: 0
i: 2, j: 0
i: 3, j: 0
i: 4, j: 0
i: 5, j: 0
i: 6, j: 0
i: 7, j: 0
i: 8, j: 0
i: 9, j: 0

How do I break out of the outer loop?

Upvotes: 11

Views: 5062

Answers (1)

Suragch
Suragch

Reputation: 512316

Using a label

Dart supports labels. Create a label name and follow it with a colon:

outerLoop:
for (int i = 0; i < 10; i++) {
  for (var j = 0; j < 10; j++) {
    print('i: $i, j: $j');
    break outerLoop;
  }
}

In the example above, the label name is outerLoop, but you could have named it something else. Calling break outerLoop breaks out of the for loop that outerLoop is in front of.

This prints:

i: 0, j: 0

Returning from a function

Another option is to put the nested loops inside a function and then just return from the function:

void myFunction() {
  for (int i = 0; i < 10; i++) {
    for (var j = 0; j < 10; j++) {
      print('i: $i, j: $j');
      return;
    }
  }
}

Upvotes: 33

Related Questions