Switch Case in Dart

In Dart, switch-case statements are a simplified version of the nested if-else statements. Its approach is the same as that in Java.

Syntax:

switch ( expression ) { 
   case value1: { 
      // Body of value1
   } break; 
   case value2: { 
      //Body of value2 
   } break; 
   .
   .
   .
   default: { 
      //Body of default case  
   } break; 
} 

The default case is the case whose body is executed if none of the above cases matches the condition.

Rules to follow in switch case:

  1. There can be any number of cases. But values should not be repeated.
  2. The case statements can include only constants. It should not be a variable or an expression.
  3. There should be a flow control i.e break within cases. If it is omitted than it will show error.
  4. The default case is optional.
  5. Nested switch is also there thus you can have switch inside switch.



Example 1: Normal switch-case statement

filter_none

edit
close

play_arrow

link
brightness_4
code

void main()
{
    int gfg = 1;
    switch (gfg) {
    case 1: {
        print("GeeksforGeeks number 1");
    } break;
    case 2: {
        print("GeeksforGeeks number 2");
    } break;
    case 3: {
        print("GeeksforGeeks number 3");
    } break;
    default: {
        print("This is default case");
    } break;
    }
}

chevron_right


Output:

GeeksforGeeks number 1

Example 2: Nested switch-case statement

filter_none

edit
close

play_arrow

link
brightness_4
code

void main()
{
    int gfg1 = 1;
    String gfg2 = "Geek";
    switch (gfg1) {
    case 1: {
        switch (gfg2) {
        case 'Geek': {
            print("Welcome to GeeksforGeeks");
        }
        }
    } break;
    case 2: {
        print("GeeksforGeeks number 2");
    } break;
    default: {
        print("This is default case");
    } break;
    }
}

chevron_right


Output:

Welcome to GeeksforGeeks



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.