super_enum_generator 0.5.0 copy "super_enum_generator: ^0.5.0" to clipboard
super_enum_generator: ^0.5.0 copied to clipboard

discontinuedreplaced by: freezed
outdated

Dev-dependency to generate sealed classes and when statements together with the super_enum.dart package.

Dart CI codecov Version Version

Super-powered enums similar to sealed classes in Kotlin

Migration From v0.3.0 to v0.4.0 #

  • DataField signature has been changed.
    • DataField(String,Type) should be replaced with DataField<Type>(String)
    • Should specify generic data types (eg: List, Map) in the following manner- DataField<List<Foo>>('foos')

Installation #

Add the following to you pubspec.yaml and replace [version] with the latest version:

dependencies:
  super_enum: ^[version]

dev_dependencies:
  super_enum_generator: ^[version]
  build_runner: ^1.7.1 // Any latest version which works with your current Dart or Flutter SDK

Example #

A Super Enum can be easily generated by annotating a private enum with @superEnum

import 'package:super_enum/super_enum.dart';

part "result.g.dart";

@superEnum
enum _Result {
  @generic
  @Data(fields: [
    DataField<Generic>('data'),
    DataField<String>('message'),
  ])
  Success,

  @object
  Error,
}

@Data() marks an enum value to be treated as a Data class.

  • One should supply a list of possible fields inside the annotation.
  • If you don't want to add fields, use @object annotation instead.
  • Fields are supplied in the form of DataField objects.
  • Each DataField must contain the name and the type of the field.
  • If the field type needs to be generic use Generic type and annotate the enum value with @generic annotation.

@object marks an enum value to be treated as an object.

NOTE: If you want to use existing classes directly without having them auto-generated and wrapped use @UseClass().

Run the build_runner command to generate the filename.g.dart part file.

 # Dart SDK: $pub run build_runner build
 # Flutter SDK: $flutter pub run build_runner build

Generated file #

@immutable
abstract class Result<T> extends Equatable {
  const Result(this._type);

  factory Result.success({@required T data, @required String message}) =
      Success<T>;

  factory Result.error() = Error<T>;

  final _Result _type;

  R when<R>(
      {@required R Function(Success<T>) success,
      @required R Function(Error<T>) error}) {
    assert(() {
      if (success == null || error == null) {
        throw 'check for all possible cases';
      }
      return true;
    }());
    switch (this._type) {
      case _Result.Success:
        return success(this as Success);
      case _Result.Error:
        return error(this as Error);
    }
  }

  Future<R> asyncWhen<R>(
      {@required FutureOr<R> Function(Success<T>) success,
      @required FutureOr<R> Function(Error<T>) error}) {
    assert(() {
      if (success == null || error == null) {
        throw 'check for all possible cases';
      }
      return true;
    }());
    switch (this._type) {
      case _Result.Success:
        return success(this as Success);
      case _Result.Error:
        return error(this as Error);
    }
  }

  R whenOrElse<R>(
      {R Function(Success<T>) success,
      R Function(Error<T>) error,
      @required R Function(Result<T>) orElse}) {
    assert(() {
      if (orElse == null) {
        throw 'Missing orElse case';
      }
      return true;
    }());
    switch (this._type) {
      case _Result.Success:
        if (success == null) break;
        return success(this as Success);
      case _Result.Error:
        if (error == null) break;
        return error(this as Error);
    }
    return orElse(this);
  }

  Future<R> asyncWhenOrElse<R>(
      {FutureOr<R> Function(Success<T>) success,
      FutureOr<R> Function(Error<T>) error,
      @required FutureOr<R> Function(Result<T>) orElse}) {
    assert(() {
      if (orElse == null) {
        throw 'Missing orElse case';
      }
      return true;
    }());
    switch (this._type) {
      case _Result.Success:
        if (success == null) break;
        return success(this as Success);
      case _Result.Error:
        if (error == null) break;
        return error(this as Error);
    }
    return orElse(this);
  }

  Future<void> whenPartial(
      {FutureOr<void> Function(Success<T>) success,
      FutureOr<void> Function(Error<T>) error}) {
    assert(() {
      if (success == null && error == null) {
        throw 'provide at least one branch';
      }
      return true;
    }());
    switch (this._type) {
      case _Result.Success:
        if (success == null) break;
        return success(this as Success);
      case _Result.Error:
        if (error == null) break;
        return error(this as Error);
    }
  }

  @override
  List get props => const [];
}

@immutable
class Success<T> extends Result<T> {
  const Success({@required this.data, @required this.message})
      : super(_Result.Success);

  final T data;

  final String message;

  @override
  String toString() => 'Success(data:${this.data},message:${this.message})';
  @override
  List get props => [data, message];
}

@immutable
class Error<T> extends Result<T> {
  const Error._() : super(_Result.Error);

  factory Error() {
    _instance ??= const Error._();
    return _instance;
  }

  static Error _instance;
}

Usage #

Below is just one of the use-case of Super Enums. It can be used wherever you want to manage state.

// Creating an StreamController of type Result<int>
final _resultController = StreamController<Result<int>>();

// Adding a success state to the stream controller
_resultController.add(Result.success(
              data: 333,
              message: 'Success',
            )),

// Adding an error state to the stream controller
_resultController.add(Result.error()),

// Listening to all the possible Result states
_resultController.stream.listen((result) {
      result.when(
        onSuccess: (data) => print(data.message), // Success
        onError: (_) => print('Error Occurred'), // Error Occurred
      );
    });

UseClass Example #

A sample UseClass() example.

class MySuccess {
  MySuccess(this.fieldA);

  final String fieldA;
}

class MyError {
  MyError(this.fieldA, this.fieldB);

  final String fieldA;
  final int fieldB;
}

@superEnum
enum _ResultUnion {
  @UseClass(MySuccess)
  Success,

  @UseClass(MyError)
  Error,
}

Getting Started #

This project is a starting point for a Dart package, a library module containing code that can be shared easily across multiple Flutter or Dart projects.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

10
likes
0
pub points
23%
popularity

Publisher

verified publisherxdsahil.dev

Dev-dependency to generate sealed classes and when statements together with the super_enum.dart package.

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

Dependencies

analyzer, build, code_builder, dart_style, source_gen, super_enum

More

Packages that depend on super_enum_generator