super_enum_generator 0.4.2

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;

//ignore: missing_return
  FutureOr<R> when<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);
    }
  }

  FutureOr<R> whenOrElse<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);
  }

  FutureOr<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 ??= 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.

0.4.2

1. Fix for "Same @UseClass() generates the wrapper twice"
   (https://github.com/xsahil03x/super_enum/issues/42)

2. Updated equatable to ^1.1.0

0.4.1

1. Hotfix for "DataFields with a name including 'T' break code generation"
   (https://github.com/xsahil03x/super_enum/issues/39)

2. Updated equatable to ^1.0.3

0.4.0

1. Added support for generic data types `DataField<List<foo>>('foos')`
   eg : List, Map, BuiltList etc

2. Added support for union types. `@UseClass()`

3. Made the generated code more cohesive with generics.

4. Bug fixes and improvements.

0.3.0

1. Added two new 'whenX' methods.
    - whenOrElse
    - whenPartial

2. Bug fixes and improvements.

0.2.0+1

Set version range for 'analyzer' and 'build' 
for removing version compatibility issues.

0.2.0

1. Make object classes singleton.

2. Make Data classes Equatable 
    * '=='
    * 'hashCode'
    * 'toString'

0.1.0

* Updated super_enum to v0.1.0.
* Added example.

0.0.1+1

Fix homepage link.

0.0.1

Initial Release.

example/example.dart

import 'package:super_enum/super_enum.dart';

part 'example.g.dart';

@superEnum
enum _Attribute {
  @Data(fields: [DataField<int>('value')])
  Strength,
  @Data(fields: [DataField<int>('value')])
  Intelligence,
  @Data(fields: [DataField<int>('value')])
  Agility,
  @Data(fields: [DataField<int>('value')])
  Dexterity,
  @Data(fields: [DataField<int>('value')])
  Endurance,
  @Data(fields: [DataField<int>('value')])
  Speed
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  super_enum_generator: ^0.4.2

2. Install it

You can install packages from the command line:

with pub:


$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:super_enum_generator/super_enum_generator.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
72
Health:
Code health derived from static analysis. [more]
99
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
86
Learn more about scoring.

We analyzed this package on Feb 12, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.5

Health issues and suggestions

Document public APIs. (-1 points)

2 out of 2 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.0 <3.0.0
analyzer >=0.39.2 <0.40.0 0.39.4
build >=0.12.6 <2.0.0 1.2.2
code_builder ^3.2.0 3.2.1
dart_style ^1.3.3 1.3.3
source_gen ^0.9.4+7 0.9.4+7
super_enum ^0.4.2 0.4.2
Transitive dependencies
_fe_analyzer_shared 1.0.3
args 1.5.2
async 2.4.0
built_collection 4.3.2
built_value 7.0.9
charcode 1.1.3
collection 1.14.12
convert 2.1.1
crypto 2.1.4
csslib 0.16.1
equatable 1.1.0
fixnum 0.10.11
glob 1.2.0
html 0.14.0+3
js 0.6.1+1
logging 0.11.4
matcher 0.12.6
meta 1.1.8
node_interop 1.0.3
node_io 1.0.1+2
package_config 1.1.0 2.0.0
path 1.6.4
pedantic 1.9.0
pub_semver 1.4.3
quiver 2.1.2+1
source_span 1.6.0
stack_trace 1.9.3
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
watcher 0.9.7+13
yaml 2.2.0
Dev dependencies
build_runner ^1.7.1
source_gen_test ^0.1.0+6
test ^1.9.4