In this tutorial, we will learn about the break statement in Dart. We will cover the basics of using the break statement to exit loops and switch statements.
A break statement is used to terminate the execution of a loop or switch statement. When a break statement is encountered, control is transferred to the statement immediately following the loop or switch.
The syntax for the break statement in Dart is:
break;
The break statement can be used in for, while, do-while loops, and switch statements to exit the current loop or switch block prematurely.
i
.i
is equal to 5.i
.void main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
print(i);
}
}
1234
i
and initialize it to 1.i
is less than or equal to 10.i
is equal to 5.i
.void main() {
int i = 1;
while (i <= 10) {
if (i == 5) {
break;
}
print(i);
i++;
}
}
1234
num
and assign a value to it.num
.num
.num
.void main() {
int num = 2;
switch (num) {
case 1:
print('Number is 1');
break;
case 2:
print('Number is 2');
break;
case 3:
print('Number is 3');
break;
default:
print('Number is not 1, 2, or 3');
}
}
Number is 2