Search code examples
flutterdartswitch-statement

Switch case with multiple values for the same case


I would like to know the syntax to set a multiple case statement in a switch / case.
For example :

String commentMark(int mark) {
    switch (mark) {
        case 0 : // Enter this block if mark == 0
            return "Well that's bad" ;
        case 1, 2, 3 : // Enter this block if mark == 1 or mark == 2 or mark == 3
            return "Gods what happend" ;
        // etc.
        default :
            return "At least you tried" ;
    }
}

I cannot find the right syntax to set multiple case (the line case 1, 2, 3 :), is it even possible in Dart ?

I did not found any informations on pub.dev documentation, neither on dart.dev.

I tried :
case 1, 2, 3
case (1, 2, 3)
case (1 ; 2 ; 3)
case (1 : 2 : 3)
case 1 : 3
and more !


Solution

  • As of Dart 3, break; is not necessary for non-empty case blocks. For empty blocks, you can list cases one after the other to get the following code execute on either one of those cases.

    String commentMark(int mark) {
        switch (mark) {
            case 0 : // Enter this block if mark == 0
                return "mark is 0" ;
            case 1:
            case 2:
            case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
                return "mark is either 1, 2 or 3" ;
            // etc.
            default :
                return "mark is not 0, 1, 2 or 3" ;
        }
    }
    
    

    Before Dart 3, if you did not want to return, you had to use break; after each block. But you don't have to do that anymore. Therefore this code below is equivalent to the one above.

    String commentMark(int mark) {
        String msg;
        switch (mark) {
            case 0 : // Enter this block if mark == 0
                msg = "mark is 0" ;
            case 1:
            case 2:
            case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
                msg = "mark is either 1, 2 or 3" ;
            // etc.
            default:
                msg = "mark is not 0, 1, 2 or 3" ;
        }
        return msg;
    }
    
    

    Also with Dart 3 came the || syntax, so this is also equivalent.

    String commentMark(int mark) {
        String msg;
        switch (mark) {
            case 0 : // Enter this block if mark == 0
                msg = "mark is 0" ;
            case 1 || 2 || 3:
                msg = "mark is either 1, 2 or 3" ;
            // etc.
            default:
                msg = "mark is not 0, 1, 2 or 3" ;
        }
        return msg;
    }
    

    Furthermore, Dart 3 introduces the switch expression, so the whole thing can also become this:

    String commentMark(int mark) {
        return switch (mark) {
          0 => "mark is 0",
          1 || 2 || 3 => "mark is either 1, 2 or 3",
          _ => "mark is not 0, 1, 2 or 3",
        };
    }