The switch Statement evaluates an expression, matches the expression’s value to a case clausee and executes the statements associated with that case. It is an alternative to the long if-else-if ladder which is a easy way to execute a different part of a code on the value of the expression.
The switch statement in dart is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression.
Syntax
switch(variable_expression){
case constant_expr1:{
//statements;
}
break;
case constant_expr2:{
//statements;
}
break;
default:{
//statements;
}
break;
}
The value of the variable_expression is tested against all cases in the switch,if matches the code block is executed right away, If no expression is matched the default block is executed.
Rules to be followed:
void main(){
var grade = "A";
switch(grade){
case "A": {
print("Excellent"); }
break;
case "B": {
print("Good");
}
break;
case "C": {
print("Fair");
}
break;
case "D": {
print("Poor");
}
break;
default: {
print("Invalid choice");
}
break;
}
}
The output is :-
Excellent