×

Dart Switch Case Statement

In the case of if-else statements, we prefer not to use the if-else ladder when there are many test conditions to be evaluated. In such a situation, it is preferable to use the Dart switch case statement, which is the simplified form of the nested if-else statement. 

Here, the single value of the variable is compared with the multiple cases. If a matching case is found, it executes a block of statements associated with that particular case, and the flow breaks out of the switch loop with the help of the break statement. 

The break statement is very important in the dart switch case loop. If we somehow forget to write the break statement, the output corresponding to each statement after the case matches the value is printed to the console. 

Let us understand its syntax :

switch( expression )  
{  
    case value - 1 :  //statement( s )  
           
Block - 1 ; 
                               
                                     break ;

   case value - 2 :  //statement( s )  
           
Block - 1 ; 
                               
                                     break ;

   case value - 3 :  //statement( s )  
           
Block - 1 ; 
                               
                                     break ;
   case value - N :  //statement( s )  
           
Block - 1 ; 
                               
                                     break ;

    default : // statement( s ) ;  
                     
}

In this switch case statement syntax, the expression can be an integer or character. The values 1, 2, n is called the case labels. They identify each case of the string, and the value of the expression is checked against these case labels only. They must always be terminated by a colon ':'. It is mandatory to have unique case labels; redundant labels cause ambiguity for the compiler. It creates confusion that a particular value should be matched against one of the cases. 

A block is multiple lines of code associated with a particular case label. After evaluating the test expression, the resultant value is compared with all the cases defined in the switch case. Whichever case label matches with the resultant value. The compiler executes the corresponding block. The break statement is used to truncate the flow out of the switch statement as soon as the value is matched with the case label. If we do not write the break statement after each case, it will execute all the cases until the program end is reached. 

At times, the resultant value does not match with any of the case labels; the statement corresponding to the default case is executed in such a situation. However, writing the default statement is entirely optional in Dart. 

Consider the following example to gain a better perspective on switch-case statements

Program

import 'dart:io' ;
void main( )
{
  // accept the marks from the user
  print( ' Enter the Marks ( 100 / 80 / 60 / 40 / 20 / 0 ) : ' ) ;
  int? n = int.parse(stdin.readLineSync( ) ! ) ;


  // switch case statement
  switch( n )
  {
    case 100 : print( ' Grades are : A+ ' ) ;
              break ;
    case 80 : print( ' Grades are : B+ ' ) ;
              break ;
    case 60 : print( ' Grades are : C+ ' ) ;
              break ;
    case 40 : print( ' Grades are : D+ ' ) ;
              break ;
    case 20 : print( ' Grades are : E+ ' ) ;
              break ;
    case 0 : print( ' Fail ' ) ;
              break ;
  }
}

Output :

Dart switch case statement

Explanation -

The marks are taken from the user in the above program and compared with different case labels. Whichever case matches, the output corresponding to that case is executed. 

Consider the following code in Dart that is a simple calculator simulation.

Program

import 'dart:io';


void main( ) {
  // printing the menu for the menu driven program
  print( " \n MENU \n Select the choice you want to perform : \n 1. ADD \n 2. SUBTRACT \n 3. MULTIPLY \n 4. DIVIDE \n 5. EXIT \n Choice you want to enter : " ) ;
  int? n = int.parse( stdin.readLineSync( ) ! ) ;


  // accept the value of the first variable from the user
  print( " \n Enter the value for x : " ) ;
  int? x = int.parse( stdin.readLineSync( ) ! ) ;


  // accept the value of the second variable from the user
  print( " \n Enter the value for y : " ) ;
  int? y = int.parse( stdin.readLineSync( ) ! ) ;


  // switch case
  switch ( n ) {


    // case 1 for addition of two numbers
    case 1 :
      int s = x + y ;
      print( ' \n Sum of the two numbers is : ' ) ;
      print( s ) ;
      break ;


    // case 2 for difference of two numbers
    case 2 :
      int d = x – y ; 
      print( ' \n Difference of the two numbers is : ' ) ;
      print( d ) ;
      break ;


    // case 3 for the multiplication of two numbers
    case 3 :
      int m = x * y ;
      print( ' \n Product of the two numbers is : ' ) ;
      print( m ) ;
      break ;


    // case 4 for the division of two numbers
    case 4 :
      int div = x ~/ y ;
      print( ' \n Quotient of the two numbers is : ' ) ;
      print( div ) ;
      break ;


    // default case if the value of the expression matches no case
    default :
      print( " Wrong choice " ) ;
  }
}

Output :

Dart switch case statement

Explanation :

In the above code, we accept the value of the variable for the test expression from the user, and the compiler checks it with all the case labels. Case Label 1 corresponds to addition operation, Label 2 to subtraction operation, Label 3 to multiplication operation, and Label 4 to division operation. When the value of the test expression matches with the case label, the values of x and y are taken from the user, and the corresponding operation is performed. 

Advantages of Switch case

The switch case statement is a simplified version of the nested if-else statement. The if-else statement unnecessarily increases the lines of code in the program and creates confusion for the reader to understand the program. Moreover, redundancy of cases occurs at times in the nested if-else statement. The switch case reduces the ambiguity of the program and enhances its readability and understandability. 


Related Topics

Dart Method Overriding

Before understanding method overriding, it is important to clear the concept of polymorphism. Polymorphism is derived from two Greek words 'Poly' which means many and 'morphs' which means many forms....

5 minutes read.

Dart If-else-if statement

If - else - if statement enables to check the set of test expressions that evaluate to Boolean True or False, and based on this true or false the particular...

2 minutes read.

Dart Basics

Dart, as earlier mentioned multiple times, is very similar to C, C++ and Java. It is an object-oriented, garbage collecting and class-based programming language. Let’s look further and see what Dart has...

10 minutes read.

Dart Type Test Operators

Type Test Operators in Dart These operators are used to check the types of expressions at runtime. Dart is a typed language, and we often want to assert that a value...

1 minute read.

Soundness in Dart

What is soundness? Soundness ensures that the program never comes across any invalid state that may lead to abrupt termination of the program. As its name suggests it ensures perfect type...

4 minutes read.

Dart Standard Input & Output

Standard Input in Dart (stdin): The standard input stream reads data both synchronously and asynchronously from the keyboard.  In Dart programming language, .readLineSync( ) function is used to accept input from the...

3 minutes read.

Dart Runes and Graphemes

Runes and Graphemes data types in Dart Runes and Graphemes Runes are the special string of Unicode UTF-32 bits that represent the special syntax. Unicode defines a unique numeric value for each...

2 minutes read.

Dart - extends, with and implements Keywords

The application development in Dart programming language using the Flutter framework, regularly experience different usage of the implements, extends and with keywords. Dart has full support for inheritance that is...

5 minutes read.

Abstract Classes in Dart

Abstract classes in Dart are those classes that only contain abstract methods  (methods that do not contain any implementation). These classes are specifically designed for the purpose of inheritance. We...

4 minutes read.

Dart Basic Program

Dart provides various convenient platforms to code and compile the program in Dart language. Some of them are: 1. Using IDE = Visual Studio code is a text editor with IDE....

3 minutes read.

Dart Symbols

Symbols data type in Dart A symbol is an object that is the representation of an operator or identifier in Dart. These are compile-time constants.  They are used in APIs that refer...

1 minute read.

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type. Every key can occur only once, while the values can be used multiple...

5 minutes read.

Dart Optional Parameters

Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not...

2 minutes read.

Dart lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.

Dart Anonymous Function

Dart functions are the user defined functions that are designed to perform specific task. The use case of the functions is that they can be directly called any number of...

3 minutes read.

Dart If statement

If statement is used to set the control on the lines of code. Using if statement, block of code is executed only if the expression in the statement returns true....

1 minute read.

Dart Objects

Apart from the built-in data types, Dart offers some other data types that have a special role to play. One of them is Objects.  Objects Objects are the foundation of the...

3 minutes read.

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly....

5 minutes read.

Dart Iterable

Iterable is a collection of elements that are accessed sequentially. These elements are accessible using the iterator getter and stepping through the values using this getter. Let us understand the setting...

6 minutes read.