What is the case keyword in Dart?

Overview

The case keyword is used in a switch statement. Each case expression must be unique. A case only takes a constant value.

Note: A case cannot be a variable or expression.

Syntax

switch(variable_expression) { 
   case constant_expr1: { 
      // statements; 
   } 
   break; 
  case constant_expr2: { 
      // statements; 
   }
   default: { 
      //statements;  
   }
   break; 
} 

Example

The following code shows how to use the case keyword in Dart.

// dart program
void main()
{
int num = 3;
switch (num) {
case 1: {
print("Shot 1");
} break;
case 3: {
print("Shot 3");
} break;
default: {
print("This is default case");
} break;
}
}

Explanation

  • Lines 2–16: We create the main() function.
  • Line 4: We declare a variable num of type int and assign a value to it.
  • Lines 5–15: We use a switch statement. The value of the num is tested against the different cases in the switch. If the value of num matches one of the cases, the corresponding code block is executed. Otherwise, the code within the default block is executed.

Note: Each case must be unique.

Free Resources