https://github.com/reginfell/dart-sealed
Codegen implementation for using with sealed annotation
https://github.com/reginfell/dart-sealed
codegen dart flutter sealed
Last synced: about 2 months ago
JSON representation
Codegen implementation for using with sealed annotation
- Host: GitHub
- URL: https://github.com/reginfell/dart-sealed
- Owner: ReginFell
- License: apache-2.0
- Created: 2019-07-24T17:14:44.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2019-09-24T19:54:44.000Z (over 5 years ago)
- Last Synced: 2025-03-29T11:51:42.433Z (2 months ago)
- Topics: codegen, dart, flutter, sealed
- Language: Dart
- Homepage:
- Size: 82 KB
- Stars: 23
- Watchers: 0
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
ᶘ ᵒᴥᵒᶅ
### SealedCodegen - 'when' operator generator for @sealed classes ###
# Getting started #
1) Add these dependencies
```yaml
dev_dependencies:
build_runner: ^1.0.0
sealed_generator: 1.0.1
```2) Mark any class you want with @sealed annotation (meta: ^1.1.7) and add part '.g.dart' to the header of you file
```dart
import 'package:meta/meta.dart';part 'result.g.dart';
@sealed
class Result with SealedResult {}class Success extends Result {
T value;Success(this.value);
}
```
3) run:
```bash
flutter packages pub run build_runner build
```
Generator will create a class OriginalClassNameSealed for you to use```dart
class SealedResult {
R when({
@required R Function(Success) success,
@required R Function(Failure) failure,
}) {
if (this is Success) {
return success(this as Success);
}
if (this is Failure) {
return failure(this as Failure);
}
throw new Exception(
'If you got here, probably you forgot to regenerate the classes? Try running flutter packages pub run build_runner build');
}
}
```4) Add with(or extends) to your sealed class, for e.g. class Result extends(with) ResultSealed
# Using #
Just create an instance of you sealed class and call when on it, for example:
```dart
var resultWidget = result.when(
success: (event) => Text(event.value),
failure: (event) => Text("Failure"),
idle: (event) => Text("idle"),
);
```And that's it, you are ready to use sealed classses with some sort of when
It is a very early version of the library, mostly a proof of concept, so contributions are highly welcomed