Dart Break Statements

Dart Break Statements

Have you ever found yourself in a situation where you needed to prematurely exit a loop or switch statements in Dart? If so you are in luck!

Dart provides a powerful tool for precisely that purpose: the break statement.

In Dart, the break statements is used to immediately exit the nearest enclosing loop or switch statement. It allows you to terminate the execution of the loop or switch block prematurely.


Here's a simple example to illustrate it basic usage:

  1. Function Declaration: The main() function serves as the entry point of the Dart program. It's where the execution begins.

  2. For Loop: Inside the main() function, there's a for loop initialized with var num = 0, which means num starts at 0. The loop condition num <= 10 specifies that the loop should continue iterating as long as num is less than or equal to 10. The loop's iterator num++ increments num by 1 in each iteration.

  3. If Statement: Inside the loop, there's an if statement checking whether num is equal to 8. If num equals 8, the code inside the if block will be executed.

  4. Break Statement: When num reaches 8, the break statement is executed. This statement immediately terminates the nearest enclosing loop, which in this case is the for loop. As a result, the loop stops iterating, and the program proceeds to the next statement after the loop.

  5. Print Statement: Before encountering the break statement, the code inside the loop prints the value of num. However, once num equals 8 and the break statement is executed, the loop terminates, and the print statement for num = 8 is never executed.

  6. End of Execution: After the loop terminates, the program execution continues with the next statement outside the loop, which in this case, there's none.