Switch Statement in Dart Language

Home » Dart » Switch Statement in Dart Language

In Dart, the switch statement provides an elegant way to simplify conditional branching based on the value of an expression. In this tutorial, we will explore the switch statement in Dart.

Switch Statement in Dart Language

With its concise syntax and flexibility, the switch statement offers an alternative to lengthy if-else chains.

switch (expression) {
case value1:
// code to execute if expression matches value1
break;
case value2:
// code to execute if expression matches value2
break;
// additional cases…
default:
// code to execute if expression matches none of the cases
}

The expression represents the value to be evaluated against different cases. Each case represents a possible value that the expression can match.

The break statement is crucial to exit the switch block after a case is matched. The default case serves as a fallback option when none of the specific cases are met.

The switch statement simplifies the process of checking multiple conditions against a single expression.

Benefits of using Switch Statement in Dart language

Improved Readability

Switch statements can make code more readable and concise compared to long if-else chains, especially when dealing with multiple branching conditions.

Multiple Value Matches

Switch allows for matching multiple values with a single expression, reducing the need for repeated checks and improving code efficiency.

Enumerations and Constants

Switch statements are particularly useful when working with enumerated types or predefined constants, where each case represents a specific value or state.

Code Organization

By grouping related cases together, switch statements can enhance code organization and maintainability, making it easier to understand and modify conditional logic.

Let’s build a simple calculator in Dart

Code snippet

Open DartPad or IntelliJ IDEA for testing this program.

 switch (operator) {
    case "+":
      result = num1 + num2;
      break;
    case "-":
      result = num1 - num2;
      break;
    case "*":
      result = num1 * num2;
      break;
    case "/":
      result = num1 / num2;
      break;
    default:
      print("Invalid operator.");
      return;
  }

The code you provided demonstrates the usage of the switch statement in Dart to perform different arithmetic operations based on the value of the operator variable.

The switch statement is used to evaluate the value of the operator variable. It acts as a branching mechanism, determining which block of code to execute based on the value of operator.

The case keyword is followed by a specific value or condition that the operator variable is being compared against. If the value of operator matches the specified case, the corresponding code block is executed.

In each case, there is code that performs a specific arithmetic operation based on the value of operator and assigns the result to the result variable.

The break statement is used to exit the switch block once the corresponding case is executed. This prevents fall-through to subsequent cases and ensures that only the relevant case block is executed.

If the value of operator does not match any of the specified cases, the default case is executed. In this case, the code block prints an error message “Invalid operator.” using the print() function.

The return statement is used to immediately exit the current function and terminate its execution when the default case is executed. This ensures that the program doesn’t continue executing further after encountering an invalid operator.

Comple Dart Program (Calculator)

main.dart

import 'dart:io';

void main() {
  print("Simple Calculator");
  print("==================");

  // Read the first number from the user
  print("Enter the first number:");
  double num1 = double.parse(stdin.readLineSync()!);

  // Read the second number from the user
  print("Enter the second number:");
  double num2 = double.parse(stdin.readLineSync()!);

  // Read the operator from the user
  print("Enter the operator (+, -, *, /):");
  String operator = stdin.readLineSync()!;

  double result = 0.0;

  // Perform the arithmetic operation based on the operator using a switch statement
  switch (operator) {
    case "+":
      result = num1 + num2;
      break;
    case "-":
      result = num1 - num2;
      break;
    case "*":
      result = num1 * num2;
      break;
    case "/":
      result = num1 / num2;
      break;
    default:
      print("Invalid operator.");
      return;
  }

  print("Result: $result");
}

Output

Simple Calculator
==================
Enter the first number:
34
Enter the second number:
44
Enter the operator (+, -, *, /):
+
Result: 78.0

Nested Switch Case in Dart

A nested switch case example refers to a situation where one switch statement is nested inside another switch statement.

This allows for more complex branching logic, where different cases of the outer switch statement lead to the execution of different inner switch statements. Let’s examine an example to illustrate the concept.

void main() {
  int outerValue = 2;
  int innerValue = 3;

  switch (outerValue) {
    case 1:
      print("Outer case 1");

      switch (innerValue) {
        case 1:
          print("Inner case 1");
          break;
        case 2:
          print("Inner case 2");
          break;
        default:
          print("Inner default case");
      }
      break;

    case 2:
      print("Outer case 2");

      switch (innerValue) {
        case 1:
          print("Inner case 1");
          break;
        case 2:
          print("Inner case 2");
          break;
        default:
          print("Inner default case");
      }
      break;

    default:
      print("Outer default case");
  }
}

The program starts by setting the values of outerValue and innerValue to 2 and 3, respectively.

The outer switch statement evaluates the value of outerValue. In this case, it matches the case 2, and the corresponding code block is executed.

Inside the case 2 block, the program encounters the inner switch statement, which evaluates the value of innerValue. The inner switch statement evaluates the value of innerValue.

In this case, it does not match either case 1 or case 2, so the default case block is executed, printing “Inner default case”.

Once the execution of the inner switch statement is complete, the program exits the outer switch block.

Finally, the program continues executing the remaining code outside the outer switch statement.

You may also like...