I have Android development background and I'm learning Flutter.

In Android it's a common practice to use Kotlin sealed classes to return a state from ViewModel e.g.

sealed class MyState {
    data class Success(val data: List<MyObject>) : MyState()
    data class Error(val error: String) : MyState()

I want to use similar pattern in Flutter and return a State object from the BLOC class. What is the best way to achieve the same in Flutter?

Solution 1: Rémi Rousselet

Such use case would be done using named factory constructors.

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

class 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;

Solution 2: Saman Sattari

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

Solution 3: Chinmay Mourya

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


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