What is "break" in Dart?

Sun, Dec 11, 2022

Read in 3 minutes

In this post we take a look at "break" keyword with some example codes.

In Dart, the break keyword is used to exit a loop, switch statement, or labeled block before its normal completion. When the break statement is executed, control is transferred to the statement immediately following the loop, switch statement, or labeled block.

Here is the syntax for the break statement in Dart:

break;

The break statement can be used within the following constructs:

  1. for loop: In a for loop, the break statement can be used to exit the loop before it has completed its full iteration. For example:
for (int i = 0; i < 10; i++) {
  if (i == 5) {
    break;
  }
  print(i);
}

In this example, the loop will iterate from 0 to 4 and then the break statement will be executed, causing the loop to terminate.

  1. while loop: A break statement can also be used within a while loop to exit the loop prematurely. For example:
int i = 0;
while (i < 10) {
  if (i == 5) {
    break;
  }
  print(i);
  i++;
}

In this example, the loop will iterate from 0 to 4 and then the break statement will be executed, causing the loop to terminate.

  1. do-while loop: Similarly, a break statement can be used within a do-while loop to exit the loop before it has completed its full iteration. For example:
int i = 0;
do {
  if (i == 5) {
    break;
  }
  print(i);
  i++;
} while (i < 10);

In this example, the loop will iterate from 0 to 4 and then the break statement will be executed, causing the loop to terminate.

  1. Switch statement: A break statement can also be used within a switch statement to exit the switch statement prematurely. For example:
var command = 'CLOSED';
switch (command) {
  case 'CLOSED':
    print('closing...');
    break;
  case 'PENDING':
    print('pending...');
    break;
  case 'APPROVED':
    print('approved...');
    break;
  case 'DENIED':
    print('denied...');
    break;
}

In this example, the break statement is used to exit the switch statement once the appropriate case has been matched.

  1. Labeled blocks: A break statement can also be used to exit a labeled block. A labeled block is a block of code that is associated with a label. For example:
outerLoop: for (int i = 0; i < 5; i++) {
  innerLoop: for (int j = 0; j < 5; j++) {
    if (j == 3) {
      break outerLoop;
    }
    print('$i $j');
  }
}

In this example, the break statement is used to exit the outer loop when the inner loop reaches j == 3.

In summary, the break statement in Dart is used to exit loops, switch statements, or labeled blocks before they have completed their full iteration or evaluation.


Shohruh AK



Category:

Dart

Tags:



See Also

What is "async" in Dart?
What is "assert" in Dart?
What is "as" in Dart language?
What is "abstract" in Dart language?
Everything you need to know about Dart language