Switch statements in Dart provide an elegant way to handle multiple conditions based on a single expression. They offer a more readable alternative to long chains of if-else statements, especially when dealing with discrete values.
The basic structure of a Dart switch statement is as follows:
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
default:
// code to execute if no case matches
}
expression
is evaluated once and compared against each case.break
keyword is used to exit the switch statement after a case is matched.default
case is optional and executed when no other case matches.Here's a practical example using a switch statement to handle days of the week:
String getDayType(String day) {
switch (day.toLowerCase()) {
case 'monday':
case 'tuesday':
case 'wednesday':
case 'thursday':
case 'friday':
return 'Weekday';
case 'saturday':
case 'sunday':
return 'Weekend';
default:
return 'Invalid day';
}
}
void main() {
print(getDayType('Monday')); // Output: Weekday
print(getDayType('Sunday')); // Output: Weekend
print(getDayType('Funday')); // Output: Invalid day
}
Dart allows case statements to fall through to the next case if no break
statement is used. This can be useful for handling multiple cases with the same logic:
void gradeStudent(int score) {
switch (score) {
case 90:
case 91:
case 92:
case 93:
case 94:
case 95:
case 96:
case 97:
case 98:
case 99:
case 100:
print('A grade');
break;
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 86:
case 87:
case 88:
case 89:
print('B grade');
break;
default:
print('Other grade');
}
}
While switch statements are powerful, they have some limitations:
To further enhance your understanding of control flow in Dart, explore these related topics:
By mastering switch statements and other control flow mechanisms, you'll be able to write more efficient and readable Dart code.