Dart Switch Statements
Learn Dart through interactive, bite-sized lessons. Build Flutter apps and master modern development.
Start Dart Journey →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.
Basic Syntax
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
}
Key Features
- The
expressionis evaluated once and compared against each case. - Case values must be compile-time constants.
- The
breakkeyword is used to exit the switch statement after a case is matched. - The
defaultcase is optional and executed when no other case matches.
Example: Days of the Week
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
}
Fall-through Behavior
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');
}
}
Best Practices
- Use switch statements when you have multiple conditions based on a single variable.
- Ensure all cases are covered, including a default case for unexpected values.
- Keep case statements simple and avoid complex logic within them.
- Consider using if-else statements for more complex conditions or when dealing with ranges of values.
Limitations
While switch statements are powerful, they have some limitations:
- Case values must be compile-time constants.
- You can't use expressions or variables as case values.
- Switch statements work best with discrete values, not ranges or complex conditions.
Related Concepts
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.