Warning: Undefined array key "lang_code" in /home/pmfnldmy/public_html/androidatc/ap/extension/classes/common.php on line 800
Switch Case Statement

Switch Case Statement

In Dart, switch case statement is a simplified form of the nested IF-Else statements. It helps to avoid long chain of IF…Else and Else…IF... Statements. A switch case statement evaluates an expression against multiple cases in order to identify the bock of code to be executed. The switch statement can have a number of possible execution paths.

The following code example, declares an int named "day" whose value represents a day. The code displays the name of the day, based on the value of day, using the switch statement. When day=2, case 2 will work, and the today variable will be Monday, then the break statement will move to outside the switch block of code. In case no statements are running, the default statement will be selected.

main() {
  int day = 2;
  String today = null;
  switch (day) {
    case 1: today = 'Sunday';
      break;
    case 2: today = 'Monday';
      break;
    case 3: today = 'Tuesday';
      break;
    case 4: today = 'Wednesday';
      break;
    case 5: today = 'Thursday';
      break;
    case 6: today = 'Friday';
      break;
    case 7: today = 'Saturday';
      break;
    default: today = 'Invalid Day'; }
    print("Today is : $today");
}


When you run the Dart program, you will get the following result:

Switch Case Statement

When you change "day" variable to 3 , and run the Dart program, you will get the following result:

Switch Case Statement

When you change "day" variable to 9 , the default statement will work , and the run result will be as follows:

switch cas dart

* This topic is a part of lesson 2 of Flutter Application Development course. For more information about this course, click here.