Skip to main content

switch case

The switch case statement is similar to the expression if, else-if, else but only allows us to compare equality (==). The switch case syntax is as follows:

switch(expression) {
case value1:
// statements
case value2:
// statements
case value3:
// statements
// default statements

If the expression result is equal to a value, then the code inside that case is executed. When the Dart code reaches the break keyword, it will break out of the switch and continue the execution of the program.

Let's see the following example in DartPad: Let's say we want to print the day of the week given a number between one and seven. Monday is equal to one, Tuesday is equal to two, and so on:

What happens if we do not add the break keyword? Well, then the next case will be executed. Try removing some of the break keywords from the previous example. What is the result?

Grouping cases

Sometimes we want to group more than one case to execute the same code. Let's see the following example in DartPad: Given a number between one and seven, we want to print if it's a weekday or weekend:

In the previous example, we grouped cases 1, 2, 3, 4, and 5 to print Is weekday, and we grouped cases 6 and 7 to print Is weekend. Also, we have a default statement that will print Wrong day in case the given number does not match any day of the week.