generic_enum 0.1.9

  • Readme
  • Changelog
  • Example
  • Installing
  • 75

Generic Enumeration Classes for Dart #

Build Status

Introduction #

Enumerations are ideal when we want to model choosing from a limited set of constant values. In Dart, the value of an enum resolves to a String.

GenericEnum is a base class for creating enumeration classes with generic value type. These classes appear to the user of the library much like a Dart enum would. For example, generic enums can be used in switch statements, to initialize variables, or as default parameters in functions and constructors.

Boilerplate #

To use this library include generic_enum and generic_enum_annotation as dependency in your pubspec.yaml file. Include generic_enum_builder, source_gen, build_runner as dev_dependencies.

To create a generic enum class, say DpiResolution, the following steps are required:

  1. Extend GenericEnum<T>. To use the serialization methods, T should have fromJson and toJson methods.
  2. Define a private const constructor that calls the super constructor and passes on the value of type T.
  3. Define the static const instances of DpiResolution. You may capitalize instance names to mark them as constants.

The following steps are optional. They are only required if one needs access to a list of all defined values and instances or if json-serialization is needed. In principle, a map containing values and instances and serialization functions could be maintained manually. When defining several generic enumeration classes it might be more convenient to use a builder.

  1. Annotate the class with @GenerateValueMap or @GenerateFromJson. Note: Since generic_enum_builder version 0.1.7 @GenerateFromJson triggers the build of the value-instance map as well as the _$<ClassName>FromJson function.

  2. Define an accessor for the private variable _$<ClassName>ValueMap.

  3. Define a name factory constructor named .fromJson pointing to the function _$<ClassName>FromJson.

    import 'package:generic_enum/generic_enum.dart';
    import 'package:generic_enum_annotation/generic_enum_annotation.dart';
    
    //   0. Add a part statement pointing to the generated file.
    part 'dpi_resolution.g.dart';
    
    //   1. Extend GenericEnum<T>
    @GenerateFromJson()   //       <----------- 4. Annotate class
    class DpiResolution extends GenericEnum<int> {
      // 2. Define a private const constructor that calls the super constructor
      //    and passes on the value of type int.
      const DpiResolution._(int value) : super(value);
    
      // 3. Define static constant instances of type DpiResolution
      static const DpiResolution LOW = DpiResolution._(90);
      static const DpiResolution MEDIUM = DpiResolution._(300);
      static const DpiResolution HIGH = DpiResolution._(600);
    
      // 5. Give access to _valueMap and
      static Map<int, DpiResolution> get valueMap => _$DpiResolutionValueMap;
    
      // 6. Define the named factory constructor .fromJson:
      factory DpiResolution.fromJson(Map<String,dynamic> json)
          => _$DpiResolutionFromJson(json);
    
    }
    
  4. Configure the build targets (and amend the generate_for entry). In your local build.yaml file add the following targets:

    targets:
      $default:
        builders:
          # Configure the builder `pkg_name|builder_name`
          generic_enum_builder|map_builder:
            # Only run this builder on the specified input.
            enabled: true
            generate_for:
              - lib/*.dart
          # Configure the builder `pkg_name|builder_name`
          generic_enum_builder|json_builder:
            # Only run this builder on the specified input.
            enabled: true
            generate_for:
              - lib/*.dart
    
  5. Build the project by running the command

    $ pub run build_runner build --delete-conflicting-outputs
    

Usage #

GenericEnum instances and their value are compile-time constants and can be used in switch statements to initalize other constants, final variables, or as parameters or default parameters in constructors and functions.

The sample class ScannerSettings (defined below) illustrates the use of a generic enum.

The value of generic enums can be accessed directly using dot notation (like in the initializer statement below).

class ScannerSettings{

  const ScannerSettings({
    this.scanMode,
    this.size,
    this.dpiResolution = DpiResolution.Medium,
    },
  ):_dipRes = dpiResolution.value; // Access value using dot-notation.

  final DpiResolution dpiResolution;
  final int _dpiRes;
  final ScanMode;
  final ScanSize;
}

Examples #

Further examples on how to define and build generic enumeration classes can be found in the library generic_enum_example.

For details of how to use generic enums as annotations and how to retrieve their value using Dart's static analyzer package see example.

Features and bugs #

Please file feature requests and bugs at the issue tracker.

0.0.1 #

Initial Version of the library.

0.0.2 #

Library now depends on built_collection.

0.0.3 #

Changed GeneralizedEnum to GenericEnum.

0.0.4 #

Amended library description.

0.0.5 #

Amended sample code in README.md.

0.0.6 #

Shortened library description.

0.1.0 #

Added json-serialization.

0.1.1 #

Added Dart docs.

0.1.2 #

Amended Dart docs.

0.1.3 #

Added serialization tests.

0.1.4 #

Amended #usage (prefix for gen. functions)

0.1.5 #

Amended documentation.

0.1.6 #

Upgraded dependencies.

0.1.7 #

Amended README.md.

0.1.8 #

Amended project homepage.

0.1.9 #

Amended project homepage to: generic_enum

example/README.md

Generic Enumeration Example #

Introduction #

GenericEnum is a base class for creating enumeration classes with generic value type. These classes appear to the user of the library much like a Dart enum would. For example, generic enums can be used in switch statements, to initialize variables, or as default parameters in functions and constructors.

Build Process #

The main section contains a step-by-step guide on how to define and build generic enumeration classes.

Generic Enums as Annotations #

GenericEnum classes have a constant constructor and as such can be used as annotations. Annotations are commonly found in source code generating libraries.

Since generic enums are normal classes they can contain methods and final fields in addition to the value field. The example below includes the getters isPrimary, isUnique, isNotNull.

As an example, we could generate an annotation class, say Constraint, that helps users select a supported Sqlite constraint.

import 'package:generic_enum/generic_enum.dart';
import 'package:generic_enum_annotation/generic_enum_annotation.dart';

part 'constraint.g.dart';

@GenerateFromJson()
class Constraint extends GenericEnum<String> {
  const Constraint._(String value) : super(value);

  static const Constraint NOT_NULL = Constraint._('NOT NULL');
  static const Constraint PRIMARY_KEY = Constraint._('PRIMARY KEY');
  static const Constraint UNIQUE = Constraint._('UNIQUE');

  static Map<String, Constraint> get valueMap => _$ConstraintValueMap;
  factory Constraint.fromJson(Map<String,dynamic> json) => _$ConstraintFromJson(json);

  bool get isPrimary => (this == PRIMARY_KEY);
  bool get isUnique => (this == UNIQUE);
  bool get isNotNull => (this == NOT_NULL);
}

The Constraint class could be used to annotate a field in the data class User.

import 'constraint.dart';
import 'table.dart';

@Table
class User{
  const User({@required this.id, @required this.userName});

  // Use generic enum as annotation
  @Constraint.PRIMARY_KEY
  final int id;

  @Constraint.NOT_NULL
  final String userName;
}

Retrieving Annotations of Type Generic Enum #

Using the package analyzer, the data model User can be traversed with the help of a SimpleElementVisitor.

When processing annotations (for example during source code generation: see method _addConstraint below), the recommended way of retrieving an annotation of type GenericEnum is via source_gen's ConstantReader.

This is because the generic enum value field is located in the parent class and ConstantReader searches parent classes if a field is not found in the current class.

import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/dart/element/visitor.dart';
import 'package:sqlite_entity/sqlite_entity.dart';
import 'package:source_gen/source_gen.dart' show TypeChecker, ConstantReader, ;
import 'package:sqlite_generator/src/type_utils.dart';

/// Sample visitor class used to traverse classed annotated with @Table
class TableVisitor extends SimpleElementVisitor {

  static var constraintChecker = TypeChecker.fromRuntime(Constraint);

  List<FieldElement> fields = [];
  Map<String,Constraint> constraints = {};

  /// Mapping field name to constraint.
  Map<String,List<Constraint>> constraints = {};

  @override
  visitFieldElement(FieldElement element) {
    fields.add(element);
    _addConstraint(element);
  }

  _addConstraint(FieldElement element){
    var annotation = element.metadata;

    if (annotation == null) return;

    // Check if annotation is of type Constraint.
    if (!_constraintChecker.isAssignableFromType(annotation.type)) return;

    // Read value of generic enum.
    // Note: ConstantReader searches for the field name 'value' in a
    // super class if it is not found in the annotation class.
    String annotationValue = ConstantReader(
      annotation.computeConstantValue(),
    ).read('value').stringValue;

    // Retrieve the Constraint instance.
    var constraintInstance = Constraint.valueMap[annotationValue];
    this.constraints.add({element.name: constraintInstance});
  }
}

For more information about source code generation see: analyzer and source_gen.

Examples #

For examples on how to create generic enums see: generic_enum_example.

Features and bugs #

Please file feature requests and bugs at the issue tracker.

Use this package as a library

1. Depend on it

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


dependencies:
  generic_enum: ^0.1.9

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

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

3. Import it

Now in your Dart code, you can use:


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

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

  • Dart: 2.7.1
  • pana: 0.13.6

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
json_annotation ^3.0.1 3.0.1
Dev dependencies
build_runner ^1.7.4
json_serializable ^3.2.5
test ^1.12.0