Dart Break

Dart break statement is used to break the current loop, and continue with the other statements after the loop.

If break statement is used in nested loops, only the immediate loop will be broken.

break statement can be used inside a For loop, While loop and Do-while loop statements.

Syntax

The syntax of break statement is

</>
Copy
break;

Examples

In the following examples, we will cover scenarios where we use break statement in different kinds of loops.

Break For Loop

In the following example, we write a For loop to print numbers from 1 to 7. But, inside the For loop, we execute break statement conditionally when i equals 5. Therefore, when i equals 5, the loop is broken.

main.dart

</>
Copy
void main() {
  for (var i = 1; i < 8; i++) {
    if (i == 5) {
      break;
    }
    print(i);
  }
}

Output

1
2
3
4

Break While Loop

In this example, we print numbers from 1 to 7 using while loop. But when i=5, we break the loop using break statement.

main.dart

</>
Copy
void main() {
  var i = 0;
  while (i < 7) {
    i++;
    if (i == 5) {
      break;
    }
    print(i);
  }
}

Output

1
2
3
4

Break Do-while Loop

In this example, we print numbers from 1 to 7 using do-while loop But when i=5, we break the do-while loop using break statement.

main.dart

</>
Copy
void main() {
  var i = 0;
  do {
    i++;
    if (i == 5) {
      break;
    }
    print(i);
  } while (i < 7);
}

Output

1
2
3
4

Conclusion

In this Dart Tutorial, we have learnt Dart break statement, and how to use this break statement inside loop statements.