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: break;
The following code snippet shows how to use the break
keyword in Dart.
void main() {// create variableint i = 1;// for loopfor (i; i < 10; i++) {if (i == 7) {// exit the loopbreak;}// display resultprint(i);}}
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.
void main() {// declare variableint i = 1;// while loopwhile (i < 10) {if (i == 7) {// exit the loopbreak;}// display resultprint(i);i++;}}
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.