Skip to content
Related Articles

Related Articles

Switch Case in Dart
  • Last Updated : 10 May, 2020

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




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;
    }
}

Output:

GeeksforGeeks number 1

Example 2: Nested switch-case statement




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;
    }
}

Output:

Welcome to GeeksforGeeks
My Personal Notes arrow_drop_up
Recommended Articles
Page :