In this chapter, we will learn about the Dart switch statement and how it can be used in the program with the help of examples.
switch Statement
The dart switch statement evaluates an expression/condition and executes the corresponding statement that match the expression/condition case.
The syntax of switch statement is:
switch(expression) {
case value1: {
// statements;
}
break;
case value2: {
//statements;
}
break;
default: {
//statements;
}
break;
}
First, the switch statement evaluates an expression inside parentheses ().
If the result of the expression matches value1, its statement is executed.
If the result of the expression matches value2, its statement is executed.
This process goes on. If there is no matching case, the default statement executes.
The default clause is also optional.
Switch Statement Example:
void main() {
var day = 3;
switch(day) {
case 1: {
print("Sunday");
}
break;
case 2: {
print("Monday");
}
break;
case 3: {
print("Tuesday");
}
break;
case 4: {
print("Wednesday");
}
break;
case 5: {
print("Thursday");
}
break;
case 6: {
print("Friday");
}
break;
case 7: {
print("Saturday");
}
break;
default: {
print("Invalid number");
}
break;
}
}
Output
Tuesday
Here is an example of a switch statement that checks the days of the week, and displays the day accordingly.
The day has value 3 (var day = 3;). Hence the case 3: matches and we get Tuesday as output.
switch With Multiple Case
In switch statements, we can also check multiple cases with the same output. For example,
void main() {
var day = 1;
switch(day) {
case 1:
case 7: {
print('Weekends');
}
break;
case 2:
case 3:
case 4:
case 5:
case 6: {
print("Weekdays");
}
break;
default: {
print("Invalid number");
}
break;
}
}
Output
Weekends
In the above example, all the numbers from 2 to 6 will print the output Weekdays and the number 1 and 7 will print the output as Weekends.
Why use switch statement?
The switch statement is similar to the if…else statement. However, the switch statement is particularly useful when there are multiple options to choose from.
The switch statement helps in increasing the readability of the program and also reduces the complexity.