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:
Function Declaration: The
main()
function serves as the entry point of the Dart program. It's where the execution begins.For Loop: Inside the
main()
function, there's afor
loop initialized withvar num = 0
, which meansnum
starts at 0. The loop conditionnum <= 10
specifies that the loop should continue iterating as long asnum
is less than or equal to 10. The loop's iteratornum++
incrementsnum
by 1 in each iteration.If Statement: Inside the loop, there's an
if
statement checking whethernum
is equal to 8. Ifnum
equals 8, the code inside theif
block will be executed.Break Statement: When
num
reaches 8, thebreak
statement is executed. This statement immediately terminates the nearest enclosing loop, which in this case is thefor
loop. As a result, the loop stops iterating, and the program proceeds to the next statement after the loop.Print Statement: Before encountering the
break
statement, the code inside the loop prints the value ofnum
. However, oncenum
equals 8 and thebreak
statement is executed, the loop terminates, and the print statement fornum = 8
is never executed.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.