Recently i looked through the document for flutter_bloc. Document is well-organized, with some good examples. One feature that caught my attention was the use of the sealed
keyword in the for the Flutter Infinite List
part of 'post_bloc.dart';
sealed class PostEvent extends Equatable {
@override
List<Object> get props => [];
}
final class PostFetched extends PostEvent {}
Sealed class
Like Kotlin and Scala, Dart has introduced sealed class in Dart3.0. A sealed class can be declared using the keyword sealed
sealed class Animal()
The sealed
modifier prevents a class from being extended or implemented outside its own library. Sealed classes are implicitly abstract.
- Cannot be constructed themselves.
- Can have factory constructors.
- Can define constructors for their subclasses to use.
The use of sealed classes allows developers to create a known, enumerable set of subtypes, use sealed
modifier. And the compiler is able to check if you have covered all subtypes of the sealed class in a switch statement. If you haven't, you might get compile errors when your switch case statement is not exclusive.
Example
sealed class Animal {}
class Cat extends Animal{}
class Dog extends Animal {}
class Bird extends Animal {}
// Abstract classes can't be instantiated.
Animal animal = Animal();
// Subclasses can be instantiated
Cat cat = Cat();
// raise a Error: The type 'Animal' is not exhaustively matched by the
// switch cases since it doesn't match 'Bird()'.
String getAnimalBark(Animal animal) {
return switch (animal) {
Cat() => 'cat bark',
Dog() => 'bog bark',
// Bird() => "bird bark"
};
}
To demonstrate the usage of sealed classes, the code defines an Animal
sealed class with three subclasses: Cat
, Dog
, and Bird
. The code also shows that , such as the Animal
class, cannot be instantiated, while subclasses can be instantiated. Finally, the code demonstrates how the switch
statement can be used with sealed classes to ensure all possible cases are covered.