Switch Statement in Dart
The switch statement is used when you want to compare a single variable against multiple possible values. It makes the code cleaner than using multiple else-if conditions.
Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code if no case matches
}
Example:
import 'dart:io';
void main() {
print('Enter a day number (1-7):');
String? input = stdin.readLineSync();
int day = int.parse(input!);
switch (day) {
case 1:
print('Monday');
break;
case 2:
print('Tuesday');
break;
case 3:
print('Wednesday');
break;
case 4:
print('Thursday');
break;
case 5:
print('Friday');
break;
case 6:
print('Saturday');
break;
case 7:
print('Sunday');
break;
default:
print('Invalid day number');
}
}
Explanation:
- The user enters a number between 1 and 7.
- Each case prints the corresponding day of the week.
- If the number is outside 1–7, the
defaultblock runs.
Sample Input/Output
Input:
day = 5
Output:
Friday
Input:
day = 7
Output:
Sunday
Input:
day = 9
Output:
Invalid day number