What is the case keyword in Dart?
Overview
The case keyword is used in a switch statement. Each case expression must be unique. A case only takes a constant value.
Note: A
casecannot be a variable or expression.
Syntax
switch(variable_expression) {
case constant_expr1: {
// statements;
}
break;
case constant_expr2: {
// statements;
}
default: {
//statements;
}
break;
}
Example
The following code shows how to use the case keyword in Dart.
// dart programvoid main(){int num = 3;switch (num) {case 1: {print("Shot 1");} break;case 3: {print("Shot 3");} break;default: {print("This is default case");} break;}}
Explanation
- Lines 2–16: We create the
main()function. - Line 4: We declare a variable
numof typeintand assign a value to it. - Lines 5–15: We use a
switchstatement. The value of thenumis tested against the different cases in theswitch. If the value ofnummatches one of the cases, the corresponding code block is executed. Otherwise, the code within the default block is executed.
Note: Each
casemust be unique.