sealed_generator 1.0.1

Codegeneration library for making 'when' statement for Dart.

ᶘ ᵒᴥᵒᶅ

SealedCodegen - 'when' operator generator for @sealed classes #

Getting started #

  1. Add these dependencies
dev_dependencies:
  build_runner: ^1.0.0
  sealed_generator: 1.0.1
  1. Mark any class you want with @sealed annotation (meta: ^1.1.7) and add part '
import 'package:meta/meta.dart';

part 'result.g.dart';

@sealed
class Result<T> with SealedResult<T> {}

class Success<T> extends Result<T> {
  T value;

  Success(this.value);
}
  1. run:
flutter packages pub run build_runner build

Generator will create a class OriginalClassNameSealed for you to use

class SealedResult<T> {
  R when<R>({
      @required R Function(Success<T>) success,
      @required R Function(Failure<T>) failure,
    }) {
    if (this is Success<T>) {
      return success(this as Success<T>);
    }
    if (this is Failure<T>) {
      return failure(this as Failure<T>);
    }
    throw new Exception(
        'If you got here, probably you forgot to regenerate the classes? Try running flutter packages pub run build_runner build');
  }
}
  1. 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:

    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

1
likes
70
pub points
0%
popularity

Codegeneration library for making 'when' statement for Dart.

Repository (GitHub)
View/report issues

Documentation

API reference

Uploader

reginfell@gmail.com

License

Apache 2.0 (LICENSE)

Dependencies

analyzer, build, flutter, meta, recase, source_gen

More

Packages that depend on sealed_generator