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?
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.
Sealed classes and interfaces represent restricted class hierarchies that provide more control over inheritance. All direct subclasses of a sealed class are known at compile time. No other subclasses may appear outside a module within which the sealed class is defined.
Here, we have a data class success object which contains the success Data and a data class Error object which contains the state of the error. This way, Sealed classes help us to write clean and concise code! That's all the information about Sealed classes and their usage in Kotlin.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With