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 theclass declaration with the sealed keyword.
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.
Exhaustiveness Checking
When a variable typed as a sealed class is evaluated in aswitch 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.
Constructor Behavior
Constructors within a sealed class are not publicly accessible for instantiation. They can only be invoked by subclasses viasuper. This ensures that only valid subtypes defined within the library can initialize the sealed parent.
Master Dart with Deep Grasping Methodology!Learn More





