×

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 super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 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.

Typedef in Dart

In Dart, typedef is used to generate a function type that we can use as a type annotation for declaring variables and return types of the function type. An alias...

4 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 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 Enumerations

Enumeration data type in Dart In simple terms, Enumerations are referred to as named constant values. Constant values are declared as enumerations using the ‘enum’ keyword.  Implementation =  enum enum_name {    ...

2 minutes read.

main function in Dart

The main( ) function is a predefined method in Dart that is also known as the entry-point of the program. The compiler begins the execution only when it comes across...

3 minutes read.

Dart Inheritance

Inheritance is a promising concept of any programming language. It is a property by which a class inherits the property of another class. Moreover, the class deriving the properties of...

5 minutes read.

Dart Arithmetic Operators

Arithmetic Operators comprises of all the operators that are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. They are binary operators that work upon two operands. Consider A...

2 minutes read.

Dart Strings

Strings data type in Dart A Dart string is a sequence of characters with an encoding of UTF-16. The text associated with string data type is enclosed withing single (‘  ’)...

3 minutes read.

Dart Function

A Dart function is a collective line of code that are targeted to perform a specialised task. Such lines of code (function) can be reused whenever we need to perform...

6 minutes read.

Dart If-else statement

In the previous section, we studied about if statements in detail. If – block is executed when the condition evaluates to true, else if the condition evaluates to false, then...

1 minute read.

Metadata in Dart

Metadata is often referred to as the data about the data. It is a  piece of data about a basic piece of data. In the case of a Dart program,...

2 minutes read.

Dart Numbers

Dart provides an in-built data type ‘Numbers’ that provides two types of values: intdouble 1. int data type int data type supports integer values, and their size or values range is platform-dependent. Integers...

4 minutes read.

Golang vs Dart

Go is the procedural programming language. It was founded in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but was launched in 2009 as the language of...

2 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 Bitwise and Shift Operators

The Bitwise operators are the operators that perform different operations bit by bit on the value of the two operands. List of Bitwise Operators in Dart Sr. Operators Description 1. & ( Binary AND ) It returns...

2 minutes read.

Dart Type inference

The task of interpreting the data types of fields, methods, local variables and most generic type arguments is handled by the static analyser. However, when not enough information is provided...

5 minutes read.

Dart HTML DOM

All web pages can be viewed as objects and exist within the browser window. We can access a web page using a web browser and it needs to be connected...

3 minutes read.

Dart Exception Handling

Exception Class – An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught...

4 minutes read.