In Dart, a switch-case statement is used to execute different code blocks based on the value of a variable. It’s a cleaner alternative to multiple if-else statements when checking a single value. Each case represents a possible value, and the default case handles any unmatched values.
Here’s an example:
void main() {
String day = 'Monday';
switch (day) {
case 'Monday':
print('Start of the week');
break;
case 'Friday':
print('Almost weekend');
break;
case 'Sunday':
print('Weekend!');
break;
default:
print('Midweek day');
}
}
I’ve applied switch-case statements in Flutter projects for state management and UI rendering. For example, based on a Here, day is checked against each case. The break statement is used to prevent fall-through; if omitted, Dart will throw an error unless the case is empty.
I’ve applied switch-case statements in Flutter projects for state management and UI rendering. For example, based on a user role like 'admin', 'editor', or 'viewer', I used switch-case to display different screens or enable/disable certain buttons.
A challenge I faced was remembering that Dart does not allow fall-through between cases, unlike some other languages, so every case must end with break, return, or be empty. A limitation is that switch-case works only with compile-time constant values (like int, String, or enums). For more complex conditions, I used if-else statements or polymorphism to handle dynamic cases.
user role like 'admin', 'editor', or 'viewer', I used switch-case to display different screens or enable/disable certain buttons.
