How to use the break keyword in Dart

Overview

We use the break keyword to break the execution of the loop. It’s used inside loops such as the for loop and the while loop.

Syntax

Syntax: break;

Code

The following code snippet shows how to use the break keyword in Dart.

Example 1

void main() {
// create variable
int i = 1;
// for loop
for (i; i < 10; i++) {
if (i == 7) {
// exit the loop
break;
}
// display result
print(i);
}
}

Explanation

  • Line 3: We declare a variable i and assign a value to it.

  • Line 5–12: We create a for loop to print numbers from one to ten. However, when i equals seven, the break expression is executed inside the for loop. As a result, the loop breaks when i equals seven.

Example 2

void main() {
// declare variable
int i = 1;
// while loop
while (i < 10) {
if (i == 7) {
// exit the loop
break;
}
// display result
print(i);
i++;
}
}

Explanation

  • Line 3: We declare a variable i and assign a value to it.

  • Line 5–12: We create a while loop to print numbers from one to nine. However, when i equals seven, the break expression is executed inside the while loop. As a result, the loop breaks when i equals seven.

Free Resources