In this tutorial you will learn about the Dart Switch Case Statement and its application with practical example.
Dart Switch Case Statement
In Dart, switch case statement is simplified form of the Nested if else statement , it helps to avoid long chain of if..else if..else statements. A switch case statement evaluates an expression against multiple cases in order to identify the block of code to be executed.
Dart Switch Case Flow Diagram
Syntax:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
switch(expression){ case value1: { // statements } break; case value2: { // statements } break; } default: { // statements } break; } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
void main() { var dayOfWeek = 5; print("W3Adda - Dart Switch Case statement."); switch(dayOfWeek){ case 1:{ print("Today is Monday."); } break; case 2: print("Today is Tuesday."); break; case 3:{ print("Today is Wednesday."); } break; case 4:{ print("Today is Thursday."); } break; case 5:{ print("Today is Friday."); } break; case 6:{ print("Today is Saturday."); } break; case 7:{ print("Today is Sunday."); } break; default:{ print("Invalid Weekday."); } break; } } |
In the above program we have an integer constant dayOfWeek with initial value of 5, and we pass this variable as expression to following switch statement, value of dayOfWeek is tested with multiple cases to identify the block of code to be executed.
When we run the above Dart program, will see the following output –
Output:-