Switch Case in Dart

Switch Case In Dart

A Switch case is used to execute the code block based on the condition. You can use a Switch case as an alternative of if-else-if condition.

Syntax

switch(expression) {
    case value1:
        statement1;
        break;
    case value2:
        statement2;
        break;
    case value3:
        statement3;
        break;
    default:
        statement4;
}

Example 1

void main() {
  var dayOfWeek = 5;
  switch (dayOfWeek) {
    case 1:
      {
        print("Today is Sunday.");
        break;
      }
    case 2:
      {
        print("Today is Monday.");
      }
      break;
    case 3:
      print("Today is Tuesday.");
      break;
    case 4:
      {
        print("Today is Wednesday.");
      }
      break;
    case 5:
      {
        print("Today is Thursday.");
      }
      break;
    case 6:
      {
        print("Today is Friday.");
      }
      break;
    case 7:
      {
        print("Today is Saturday.");
      }
      break;
    default:
      {
        print("Invalid Weekday.");
      }
      break;
  }
}
Show Output

Example 2

import "dart:io";

void main() {
  print("Enter the number:");
  int? n = int.parse(stdin.readLineSync()!);
  switch (n) {
    case 1:
      print("January");
      break;
    case 2:
      print("Febuary");
      break;
    case 3:
      print("March");
      break;
    case 4:
      print("April");
      break;
    case 5:
      print("May");
      break;
    case 6:
      print("June");
      break;
    case 7:
      print("July");
      break;
    case 8:
      print("August");
      break;
    case 9:
      print("September");
      break;
    case 10:
      print("October");
      break;
    case 11:
      print("November");
      break;
    case 12:
      print("December");
      break;
    default:
      print("Out of range");
  }
}
Show Output