dart switch case code example

Example 1: switch case in dart

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

Example 2: switch case in flutter

void main() { 
   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; 
   } 
}

Example 3: dart switch with classes

class Foo {
  Foo getAnother(Foo foo) {
    switch (foo.runtimeType) {
      case Bar:
        return new Bar();
      case Baz:
        return new Baz();
    }
    return null;
  }
}

Tags:

Misc Example