Are there any sealed classes alternatives in Dart 2.0?

Such use case would be done using named factory constructors.

It requires a lot more code, but the behavior is the same.

class MyState {
  MyState._();

  factory MyState.success(String foo) = MySuccessState;
  factory MyState.error(String foo) = MyErrorState;
}

class MyErrorState extends MyState {
  MyErrorState(this.msg): super._();

  final String msg;
}

class MySuccessState extends MyState {
  MySuccessState(this.value): super._();

  final String value;
}

Rémi Rousselet's answer is somehow correct but as sindrenm mentioned:

Unfortunately, this isn't the same thing. Kotlin sealed classes guarantee that there are no other implementations of the given class outside of the file they're defined in. That means you can exhaust when statements (switch in Dart) by just providing all possible alternatives as cases, not having to think about potential sub-classes elsewhere

While there is an active discussion about this feature on dart language: Algebraic Data Types, but there is some libraries that can help you implement this behavior. You can use this libraries:

Sealed Unions

Super Enum

Sealed Class

And if you are using BLoC library you can use this lib:

Sealed Flutter Bloc

I hope that dart language add this feature ASAP


Here is the package for the Sealed Classes/Unions in Flutter

Freezed

This Package provided the features to deal with Data Classes, Sealed Class in Dart/Flutter

Here is the link which explains the beast use of freezed package in Flutter

Use of Freezed Package in Flutter/Dart

Tags:

Dart

Flutter