Switch case in dart :
Switch is used to avoid if-else ladder in dart. The switch block takes one expression and each switch block takes n different case blocks. Based on the expression result, it moves to a specific case block. Dart switch block supports integer, string, compile-time constant and enumerated types.
The syntax of switch block :
switch(expression){
case a:
//code for case a
break;
case b:
//code for case b
break;
case c:
//code for case c
break;
default:
//code for default
}
Here, the expression is compared with the value of each case. Note that the data type of expression and case should be the same. We can have unlimited number of switch cases. Each switch case should be different. The program will keep checking each one of these switch cases from top to bottom. If any case is matched, it executes that case block.
default block executes if all case are failed.
switch block with break and default :
main() {
var v = 1;
switch (v) {
case 1:
print("One");
break;
case 2:
print("Two");
break;
case 3:
print("Three");
break;
case 4:
print("Four");
break;
case 5:
print("Five");
break;
default:
print("Unknown");
}
}
This switch block takes one integer v and compares it with five different case statements. If any of the case statement is equal to v, it will execute that print statement and exit from the switch block.
In the above example, it will print One because the value of v is 1.
The default block will execute only if the value of v is not 1, 2, 3, 4 or 5.
Switch case with two same cases:
We can have two cases with equal values. But,it will execute only the first one.
main() {
var v = 1;
switch (v) {
case 1:
print("One");
break;
case 1:
print("Two");
break;
}
}
The above example will print One. We should not use two or more case blocks with equal values.
Switch case with continue :
The continue statement is used inside a case statement to execute a different case statement. You need to use one label with the continue statement and the same label is used above the required case statement. break is not required if you are using continue.
main() {
var v = 'two';
switch (v) {
case 'one':
print('One : 1');
break;
case 'two':
print('Two : 2');
continue evenCase;
case 'three':
print('Three : 3');
break;
evenCase:
case 'even':
print('And it is even.');
}
}
This program will print:
Two : 2
And it is even.
First, it executes the print statement defined for case ‘two’. Then it moves to case ‘even’.
Switch case with throw :
main() {
var v = 0;
switch (v) {
case 0:
throw IntegerDivisionByZeroException();
default:
print("100/$v = ${100 / v}");
}
}
This program will divide 100 by a user-provided number and print that on the console. If the value of that is 0, it will throw one IntegerDivisionByZeroException__
.