Open In App

Switch Case in Dart

Last Updated : 26 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Dart, switch-case statements are a great tool for managing multiple conditions in a clean and organized way. They serve as a more efficient alternative to lengthy if-else chains, making your code easier to read and maintain.

Syntax:

switch (expression) { 
case value1:
// Body of value1
break;

case value2:
// Body of value2
break;

// Add more cases as needed

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:

  • There can be any number of cases. But values should not be repeated.
  • The case statements can include only constants. It should not be a variable or an expression.
  • There should be a flow control i.e. break within cases. If it is omitted then it will show an error.
  • The default case is optional.
  • The nested switch is also there thus you can have a switch inside the switch.
Switch


Normal switch-case statement

Example:

Dart
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


Nested switch-case statement

Example:

Java
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

Conclusion

Switch-case statements in Dart offer a handy way to manage multiple constant conditions, making them a great alternative to lengthy if-else chains. One key difference is that switch statements focus solely on compile-time constants. While it's not always necessary to include a break statement, skipping it can lead to some unexpected behavior, as it allows the program to "fall through" to the next case. You can also add a default case to catch any conditions that don't match the others. Interestingly, Dart supports nested switch-case statements too, although they're not used as often.


Next Article
Article Tags :

Similar Reads