How to break out of nested loops in Dart
Asked Answered
T

1

11

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?

Tolbutamide answered 10/12, 2021 at 5:25 Comment(0)
T
33

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;
    }
  }
}
Tolbutamide answered 10/12, 2021 at 5:25 Comment(1)
I wanted to link to labels in the documentation, but I couldn't find a good place. Let me know if you know where it is.Tolbutamide

© 2022 - 2025 — McMap. All rights reserved.