×

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

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.

Dart Built-in Data Types

A data type defines the type of value a variable can hold, such as integer, double, or string.  Dart supports two data types:  1. Built-in data types : These are the data...

1 minute read.

Dart Object-Oriented Concepts

Dart is a programming language that supports object-oriented programming. It is focused on the objects that are real-world entities and supports all the concepts of OOPS, such as objects, classes,...

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

Dart Syntax

In the previous tutorial, we coded our first program in Dart on various platforms understanding the basic functionality of each line of code.  Let us understand the syntax for Dart language...

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

C++ vs Dart

Difference between C++ and Dart C++ is an object-oriented programming language developed in 1980 by Bjarne Stroustrup. It has wide real-world applications with various in-built functions and a very vast library...

1 minute read.

Builder Classes in Dart

Before understanding builder classes, let us understand about Flutter that makes the best use of the builder classes. Flutter is actually not a programming language, it is a software development...

6 minutes read.

Dart Construtors

Constructors are the very important concept in any programming language. They are the special functions created in the classes to allocate memory to the objects of that class when created...

4 minutes read.

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

4 minutes read.

Dart Isolates

Dart successfully supports asynchronous programming which runs our program without any hindrance. This asynchronous programming is used to achieve concurrency. Dart supports concurrent programming with features such as ‘ async-await...

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

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.

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.

Rust vs Dart

Rust is a system-level programming language that stands next to C ++ in terms of syntax, but offers greater speed and memory security. Dart, on the other hand, is an...

2 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 Future and Stream

Before understanding Future and Stream in Dart, we need first to get familiar with two terms : Synchronous and Asynchronous Programming.  In synchronous programming, a single operation is handled at a...

9 minutes read.

Dart Queues

A queue is a user-defined collection of data. It is based on the FIFO principle ( First In First Out ) which implies that the element to be inserted first,...

3 minutes read.

Dart Sets

Sets data type in Dart A set is an unordered collection of items that are unique. Dart infers that sets tale strings as values. Example, var languages = { ‘Dart’ , ‘Flutter’, ‘Python’,...

3 minutes 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.