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 Sealed Classes


Share

Dart Sealed Classes

A sealed class is a class with a fixed list of subclasses.

You create one with the sealed keyword before class.

All the direct subclasses must be written in the same file as the sealed class, so Dart knows every one of them:

Example

sealed class Shape {}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}

class Square extends Shape {
  final double side;
  Square(this.side);
}

void main() {
  Shape a = Circle(2);
  Shape b = Square(3);
  print(a is Circle);
  print(b is Square);
}
Try it Yourself »

Result:

true
true

In this example, a Shape is always a Circle or a Square, and nothing else.

A sealed class is also abstract, so you cannot create an object of the sealed class itself:

Example

sealed class Shape {}

class Circle extends Shape {}

void main() {
  var s = Shape();
  print(s);
}
Try it Yourself »

Result:

main.dart:6:11: Error: The class 'Shape' is abstract and can't be instantiated.
  var s = Shape();
          ^^^^^

Exhaustive Switch

The big advantage of a sealed class is in switch expressions.

Because Dart knows all the subclasses, it can check that a switch handles every one of them.

You do not need a _ case:

Example

sealed class Shape {}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}

class Square extends Shape {
  final double side;
  Square(this.side);
}

double area(Shape shape) {
  return switch (shape) {
    Circle c => 3.14 * c.radius * c.radius,
    Square s => s.side * s.side,
  };
}

void main() {
  print(area(Circle(2)));
  print(area(Square(3)));
}
Try it Yourself »

Result:

12.56
9.0

The case Circle c matches when the shape is a Circle, and puts it in the variable c with the type Circle.

That is why you can use c.radius in the result.

You can also use object patterns to get the fields directly:

Example

sealed class Shape {}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}

class Square extends Shape {
  final double side;
  Square(this.side);
}

String describe(Shape shape) {
  return switch (shape) {
    Circle(:var radius) => 'A circle with radius $radius',
    Square(:var side) => 'A square with side $side',
  };
}

void main() {
  print(describe(Circle(2)));
  print(describe(Square(3)));
}
Try it Yourself »

Result:

A circle with radius 2.0
A square with side 3.0


A Missing Case Is an Error

Now, let us add a new subclass, Triangle, but forget to handle it in the switch.

Dart finds the problem before the program runs, and shows which type is missing:

Example

sealed class Shape {}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}

class Square extends Shape {
  final double side;
  Square(this.side);
}

class Triangle extends Shape {
  final double base;
  final double height;
  Triangle(this.base, this.height);
}

double area(Shape shape) {
  return switch (shape) {
    Circle c => 3.14 * c.radius * c.radius,
    Square s => s.side * s.side,
  };
}

void main() {
  print(area(Circle(2)));
}
Try it Yourself »

Result:

main.dart:20:18: Error: The type 'Shape' is not exhaustively matched by the switch cases since it doesn't match 'Triangle()'.
 - 'Shape' is from 'main.dart'.
Try adding a wildcard pattern or cases that match 'Triangle()'.
  return switch (shape) {
                 ^

This is very helpful in big programs.

When you add a new subclass, Dart shows you every switch that you need to update.

Add the missing case, and the program runs again:

Example

sealed class Shape {}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}

class Square extends Shape {
  final double side;
  Square(this.side);
}

class Triangle extends Shape {
  final double base;
  final double height;
  Triangle(this.base, this.height);
}

double area(Shape shape) {
  return switch (shape) {
    Circle c => 3.14 * c.radius * c.radius,
    Square s => s.side * s.side,
    Triangle t => t.base * t.height / 2,
  };
}

void main() {
  print(area(Circle(2)));
  print(area(Square(3)));
  print(area(Triangle(4, 5)));
}
Try it Yourself »

Result:

12.56
9.0
10.0

Sealed vs Abstract

With a normal abstract class, anyone can add a new subclass in another file, so Dart can never know all the subclasses.

That is why a switch over an abstract class needs a _ case, even when you have handled every subclass you wrote:

Example

abstract class Shape {}

class Circle extends Shape {}

class Square extends Shape {}

String name(Shape shape) {
  return switch (shape) {
    Circle() => 'Circle',
    Square() => 'Square',
  };
}

void main() {
  print(name(Circle()));
}
Try it Yourself »

Result:

main.dart:8:18: Error: The type 'Shape' is not exhaustively matched by the switch cases since it doesn't match 'Shape()'.
 - 'Shape' is from 'main.dart'.
Try adding a wildcard pattern or cases that match 'Shape()'.
  return switch (shape) {
                 ^

Change abstract to sealed, and the same switch works.


A Real-World Example

Sealed classes are often used for results that can be one of a few cases, like a payment that either succeeds or fails:

Example

sealed class PaymentResult {}

class Success extends PaymentResult {
  final double amount;
  Success(this.amount);
}

class Failure extends PaymentResult {
  final String reason;
  Failure(this.reason);
}

PaymentResult pay(double amount, double balance) {
  if (amount > balance) {
    return Failure('Not enough money');
  }
  return Success(amount);
}

void main() {
  for (var amount in [20.0, 500.0]) {
    var message = switch (pay(amount, 100)) {
      Success(:var amount) => 'Paid $amount',
      Failure(:var reason) => 'Payment failed: $reason',
    };
    print(message);
  }
}
Try it Yourself »

Result:

Paid 20.0
Payment failed: Not enough money

Remember: Use a sealed class when you know all the possible subtypes, and you want Dart to check that your code handles each one.



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.