Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Switch Expressions


Share

Dart Switch Expressions

In the Switch chapter, you learned the switch statement, which runs different code for different values.

Dart 3 also has a switch expression.

An expression is code that gives a value, so a switch expression gives you a result that you can store in a variable, return or print.

Each case is written as pattern => result, and the cases are separated by commas:

Example

void main() {
  var day = 3;

  var name = switch (day) {
    1 => 'Monday',
    2 => 'Tuesday',
    3 => 'Wednesday',
    4 => 'Thursday',
    5 => 'Friday',
    6 => 'Saturday',
    7 => 'Sunday',
    _ => 'Invalid day',
  };

  print(name);
}
Try it Yourself »

Result:

Wednesday

Example Explained

  • The value in the parentheses, day, is compared with each case from top to bottom.
  • The first case that matches is used, and its result becomes the value of the whole switch.
  • The wildcard _ matches any value, so it works like default in a switch statement.
  • There is no case keyword, no colon, and no break.
  • The whole switch ends with a semicolon, because it is part of the statement var name = ...;.

Here is the same program written with a switch statement, so you can compare:

Example

void main() {
  var day = 3;
  String name;

  switch (day) {
    case 1:
      name = 'Monday';
    case 2:
      name = 'Tuesday';
    case 3:
      name = 'Wednesday';
    case 4:
      name = 'Thursday';
    case 5:
      name = 'Friday';
    case 6:
      name = 'Saturday';
    case 7:
      name = 'Sunday';
    default:
      name = 'Invalid day';
  }

  print(name);
}
Try it Yourself »

Result:

Wednesday

The switch expression is shorter, and you do not need to assign the variable in every case.

Switch statementSwitch expression
Gives a valueNoYes
Case syntaxcase 1:1 =>
Default casedefault:_ =>
Each case can haveMany statementsOne expression
Best forDoing thingsChoosing a value


Exhaustiveness

A switch expression must always give a value.

That is why Dart checks that the cases cover every possible value.

This check is called exhaustiveness checking.

An int has a huge number of possible values, so without the _ case, this program does not run:

Example

void main() {
  var day = 3;

  var name = switch (day) {
    1 => 'Monday',
    2 => 'Tuesday',
    3 => 'Wednesday',
  };

  print(name);
}
Try it Yourself »

Result:

main.dart:4:22: Error: The type 'int' is not exhaustively matched by the switch cases since it doesn't match 'int()'.
Try adding a wildcard pattern or cases that match 'int()'.
  var name = switch (day) {
                     ^

With an enum or a bool, Dart knows all the possible values.

If you list them all, you do not need _:

Example

enum Light { red, yellow, green }

void main() {
  var light = Light.yellow;

  var action = switch (light) {
    Light.red => 'Stop',
    Light.yellow => 'Wait',
    Light.green => 'Go',
  };

  print(action);
}
Try it Yourself »

Result:

Wait

Tip: Leave out _ when you can.

If you add a new value to the enum later, Dart shows an error for every switch that forgets it.


Logical-or Patterns

Use || between patterns when several values should give the same result.

This is called a logical-or pattern:

Example

String dayType(String day) {
  return switch (day) {
    'Sat' || 'Sun' => 'Weekend',
    'Mon' || 'Tue' || 'Wed' || 'Thu' || 'Fri' => 'Weekday',
    _ => 'Unknown',
  };
}

void main() {
  print(dayType('Sun'));
  print(dayType('Tue'));
  print(dayType('Abc'));
}
Try it Yourself »

Result:

Weekend
Weekday
Unknown

Relational Patterns

A relational pattern compares the value with a comparison operator, like >=, < or ==.

This is perfect for ranges, like turning a score into a grade:

Example

String grade(int score) {
  return switch (score) {
    >= 90 => 'A',
    >= 80 => 'B',
    >= 70 => 'C',
    >= 60 => 'D',
    _ => 'F',
  };
}

void main() {
  print(grade(95));
  print(grade(83));
  print(grade(42));
}
Try it Yourself »

Result:

A
B
F

The cases are checked from top to bottom, so a score of 95 gets 'A' and never reaches the other cases.

Use && to combine two relational patterns into a range:

Example

String ageGroup(int age) {
  return switch (age) {
    < 0 => 'Invalid',
    >= 0 && <= 12 => 'Child',
    >= 13 && <= 19 => 'Teenager',
    _ => 'Adult',
  };
}

void main() {
  print(ageGroup(8));
  print(ageGroup(16));
  print(ageGroup(45));
}
Try it Yourself »

Result:

Child
Teenager
Adult

Guards with when

A guard is an extra condition for a case.

You write it after the pattern with the keyword when.

The case only matches if the pattern matches and the condition is true:

Example

String describe((String, int) product) {
  return switch (product) {
    (var name, var stock) when stock == 0 => '$name is sold out',
    (var name, var stock) when stock < 5 => 'Only $stock $name left',
    (var name, _) => '$name is in stock',
  };
}

void main() {
  print(describe(('Apple', 0)));
  print(describe(('Banana', 3)));
  print(describe(('Cherry', 50)));
}
Try it Yourself »

Result:

Apple is sold out
Only 3 Banana left
Cherry is in stock

In this example, each case is a record pattern, from the Patterns chapter.

The pattern unpacks the record into name and stock, and the guard checks the stock.

Note: Dart does not look inside a guard when it checks exhaustiveness.

That is why the last case has no guard, so that every product is covered.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.