Switch Case in Dart#
Overview#
The switch
case in Dart is a control flow statement that allows you to execute one code block from multiple possible cases based on the value of an expression. It provides a cleaner and more organized alternative to multiple if-else
statements when dealing with many conditions.
Basic Switch-Case Structure#
The switch
statement evaluates an expression and compares its value against multiple case
labels. When a match is found, the corresponding code block is executed.
How It Works#
- Evaluation: The
switch
statement evaluates an expression. - Matching: It compares the expression’s value to each
case
label. - Execution: Executes the block of code associated with the matched
case
. - Break: The
break
statement is used to exit theswitch
block once a case has been executed, preventing further cases from being executed. - Default: The
default
case is optional and runs if no other cases match. It acts like anelse
in anif-else
statement.
Rules and Restrictions#
- The expression in the
switch
statement must be of typeint
,String
, or an enum. - Each
case
must be a constant value. - Without a
break
,continue
, orreturn
statement in acase
block, execution will “fall through” to the next case, which can lead to unintended behavior.
Case and Default Clauses#
- Case Clauses: Define specific values to match against the expression. Each
case
must be unique and constant. - Default Clause: Optionally handles any cases not explicitly handled by other
case
labels. It ensures that there is a fallback option.
Example#
void main() {
String grade = 'B';
switch (grade) {
case 'A':
print('Excellent');
break;
case 'B':
print('Good');
break;
case 'C':
print('Fair');
break;
case 'D':
print('Poor');
break;
default:
print('Fail');
}
}
In this example, the output will be “Good” because the grade value is ‘B’.
Switch-Case with Break and Continue#
-
Break: Ends the execution of the current case block and exits the switch statement. It prevents the code from “falling through” to subsequent cases.
-
Continue: Although not typically used in a switch statement, continue can be employed in loops inside a switch case to skip the rest of the loop’s current iteration.
Example with Break and Continue#
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
for (int num in numbers) {
switch (num) {
case 2:
print('Number is 2');
continue; // Skip the rest of the loop for this iteration
case 4:
print('Number is 4');
break; // Exit the switch and loop
default:
print('Number is $num');
}
}
}
In this example:#
- When num is 2, “Number is 2” is printed, and the loop continues to the next iteration.
- When num is 4, “Number is 4” is printed, and the break statement exits the loop.
Overall#
The switch case in Dart provides a structured way to handle multiple conditions based on a single expression. It simplifies code maintenance by replacing complex if-else chains with a more readable format, and the optional default case ensures there’s always a fallback.