Last updated:
0 purchases
sealed class
Sealed Class Generator #
sealed_class:
sealed_class_generator:
Fix Dart's lack of a sealed class.
Inspired by Kotlin's implementation and by Sealed Unions.
With this lib you can generate an unlimited amount of sealed subclasses.
Installation #
dependencies:
sealed_class: 3.0.0
dev_dependencies:
sealed_class_generator: 3.0.0
build_runner: X.X.X
copied to clipboard
How to use: #
A complete example is found in the example.
Define your Sealed class by annotating it with @Sealed()
part 'yourfilename.g.dart';
@Sealed()
abstract class Result{}
copied to clipboard
Add the subclasses to the annotation.
part 'yourfilename.g.dart';
@Sealed([Failure, Success])
abstract class Result{}
copied to clipboard
Your subclasses should implement your sealed class.
@Sealed([Failure, Success])
abstract class Result {}
class Failure implements Result {
final String errorMessage;
Failure(this.errorMessage);
}
class Success implements Result {
final String data;
Success(this.data);
}
copied to clipboard
The complete file should now look like this:
import 'package:sealed_class/sealed_class.dart';
part 'yourfilename.g.dart';
@Sealed([Failure, Success])
abstract class Result {}
class Failure implements Result {
final String errorMessage;
Failure(this.errorMessage);
}
class Success implements Result {
final String data;
Success(this.data);
}
copied to clipboard
To make it compile run the following command in the terminal:
flutter packages pub run build_runner build --delete-conflicting-outputs
copied to clipboard
You can do:
void main() {
final someResult = Success("Woohoo Sealed classes in Dart");
someResult.continued(
(failure) {
print("Oh no it failed with errorMessage: ${failure.errorMessage}");
},
(success) {
print(success.data);
},
);
//Or if you want to reduce it to another value use `join`
final someOtherResult = Failure("Some Error Message");
final mapResult = someOtherResult.join(
(failure) => failure.errorMessage,
(success) => success.data,
);
print(mapResult);
}
copied to clipboard
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.