Ads by ProfitSence
Close

Dart Switch Case

Last Updated on Wednesday 5th Oct 2022

dart switch

Switch statements in Dart compare integer, string, or compile-time constants using ==. The compared objects must all be instances of the same class (and not of any of its subtypes), and the class must not override ==. Enumerated types work well in switch statements.

dart case

The switch statement takes the following form.

			
					switch (variable) {
   case value1:
      // code
      break;
   case value2:
      // code
      break;
   default:
     // code
}

			
	
  • Based on the value of the variable in parentheses, which can be an int, String or compile-time constant, switch will redirect the program control to one of the case.
  • Each case keyword takes a value and compares that value using == to the variable after the switch keyword.
  • The break keyword tells Dart to exit the switch statement.
  • If none of the case values match the switch variable, then the code after default will be executed.
			
					int number = 1;
switch(number) {
  case 0:
    print('zero!');
    break; // The switch statement must be told to exit, or it will execute every case.
  case 1:
    print('one!');
    break;
  case 2:
    print('two!');
    break;
  default:
    print('choose a different number!');
}

			
	

flutter switch case

Switch statements are great when there are many possible conditions for a single value.

  • The default case is optional and All case expression must be unique.
  • The case statements can include only constants. It cannot be a variable or an expression.
  • There can be any number of case statements within a switch.
			
					  var grade = "A";

  switch (grade) {
    case "A":
      print("Excellent");
      break;

    case "B":
      print("Good");
      break;

    case "C":
      print("Fair");
      break;

    case "D":
      print("Poor");
      break;

    default:
      print("Invalid choice");
      break;
  }