5 Dart Switch Case

5 Dart Switch Case

AI Reading

Quick summary of this article

This article demonstrates how to use a Dart switch case statement to handle different day-of-the-week values. The code assigns a string to a variable and then uses a switch to compare it against multiple case labels, printing a specific message for each day. It also includes a default clause to catch any invalid input.

  • The switch statement evaluates the variable `day` and matches it against string case labels like 'Monday' and 'Friday'.
  • Each case prints a unique message, such as "It's Monday, the start of the work week." for Monday.
  • A `break` statement is used after each case to stop execution and avoid falling through to the next case.
  • The `default` case handles any value that doesn't match the listed days, printing "Not a valid day."
  • This structure provides a clean, readable way to execute different code blocks based on a single variable's value.
void main() {
  String day = 'Monday';

  switch (day) {
    case 'Sunday':
      print('It\'s Sunday, time to relax!');
      break;
    case 'Monday':
      print('It\'s Monday, the start of the work week.');
      break;
    case 'Tuesday':
      print('It\'s Tuesday, the second day of the work week.');
      break;
    case 'Wednesday':
      print('It\'s Wednesday, middle of the week.');
      break;
    case 'Thursday':
      print('It\'s Thursday, almost the weekend.');
      break;
    case 'Friday':
      print('It\'s Friday, the end of the work week.');
      break;
    case 'Saturday':
      print('It\'s Saturday, time to enjoy the weekend!');
      break;
    default:
      print('Not a valid day.');
  }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *