Skip to main content
A sealed class is a class modifier that restricts the inheritance hierarchy to a fixed, enumerable set of subtypes defined within the same library. It implicitly marks the class as abstract and enables the Dart compiler to perform exhaustiveness checking on switch expressions and statements.

Syntax and Declaration

Declare a sealed class by prefixing the class declaration with the sealed keyword.
sealed class Response {}

Core Characteristics

  • Implicitly Abstract: Sealed classes cannot be instantiated directly. They serve strictly as a contract for subtypes.
  • Library-Level Scope: All direct subtypes must be declared in the same library (typically the same file) as the sealed class.
  • Exhaustiveness: The compiler tracks every possible subtype. This enables static verification that all types are handled in control flow structures.

Subtype Constraints

Direct subtypes of a sealed class must adhere to strict modifier rules to maintain the integrity of the hierarchy. A subtype must be declared with one of the following modifiers:
  • final: Closes the hierarchy; the subtype cannot be extended or implemented.
  • base: Allows extension but prohibits implementation.
  • sealed: Continues the sealed hierarchy, requiring its own subtypes to be defined in the same library.
Hierarchy Definition:
// defined in api_response.dart

sealed class ApiResponse {}

// Subtype 1: Closed hierarchy
final class Success extends ApiResponse {
  final String data;
  Success(this.data);
}

// Subtype 2: Open for extension, closed for implementation
base class Failure extends ApiResponse {
  final Exception error;
  Failure(this.error);
}

// Subtype 3: Continues the sealed chain
sealed class Loading extends ApiResponse {}
final class InitialLoading extends Loading {}

Exhaustiveness Checking

When a variable typed as a sealed class is evaluated in a switch statement or expression, Dart enforces coverage of every defined subtype. If a subtype is missing and no default case is provided, the code raises a compile-time error.
String handleResponse(ApiResponse response) {
  // Compiler enforces that Success, Failure, and Loading are handled
  return switch (response) {
    Success(data: var d) => 'Data: $d',
    Failure(error: var e) => 'Error: $e',
    // Omission of 'Loading' here results in a compilation error.
    Loading() => 'Please wait...',
  };
}

Constructor Behavior

Constructors within a sealed class are not publicly accessible for instantiation. They can only be invoked by subclasses via super. This ensures that only valid subtypes defined within the library can initialize the sealed parent.
sealed class Shape {
  final double area;
  
  // Only accessible to subclasses in this file
  const Shape(this.area); 
}
Master Dart with Deep Grasping Methodology!Learn More