Skip to main content
A labeled statement prefixes a specific statement (typically a loop or a switch) with an identifier followed by a colon. This identifier serves as a target for break and continue keywords, allowing control flow to bypass the default behavior of terminating or continuing only the innermost enclosing scope.

Syntax

A label is declared using a valid Dart identifier followed by a colon (:), placed immediately before the target statement.
labelName:
statement
To target the label, reference the identifier after the control flow keyword:
break labelName;
// or
continue labelName;

Mechanics

  • Scope: The label identifier is only visible within the statement it prefixes.
  • Targeting:
    • break labelName;: Terminates the execution of the statement associated with labelName. Control transfers to the first statement immediately following the labeled block.
    • continue labelName;: Terminates the current iteration of the loop associated with labelName and transfers control to the loop’s update expression or condition check.

Examples

Labeled Break

In this example, break outerLoop terminates the outer for loop entirely, rather than just the inner loop.
void main() {
  outerLoop: // Label declaration
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      if (i == 1 && j == 1) {
        break outerLoop; // Exits the labeled statement (outerLoop)
      }
      print('i: $i, j: $j');
    }
  }
  print('Done');
}
Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
Done

Labeled Continue

In this example, continue outerLoop skips the remainder of the inner loop and the remainder of the current iteration of the outer loop, proceeding directly to the next increment of i.
void main() {
  outerLoop: // Label declaration
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      if (j == 1) {
        continue outerLoop; // Jumps to next iteration of outerLoop
      }
      print('i: $i, j: $j');
    }
  }
}
Output:
i: 0, j: 0
i: 1, j: 0
i: 2, j: 0
Master Dart with Deep Grasping Methodology!Learn More