generic_enum_example 0.1.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 50

Generic Enum Example #

Build Status

Introduction #

GenericEnum is a base class for creating generic classes with a fixed set of static constant instances. These classes appear to the user 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.

This library demonstrates how to define and build generic enumeration classes.

Starting Point #

This package provides a complete example on how to define and build generic enumeration classes. As a starting point users could clone this repository, add their own generic enum classes to the folder lib and build the library. Build instructions are provided below.

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.

  2. Define an accessor for the private variable _$DpiResolutionValueMap.

  3. Define a name factory constructor named .fromJson pointing to the function _$DpiResolutionFromJson.

    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
    

    The generated file dpi_resolution.g.dart should have the following content:

    // GENERATED CODE - DO NOT MODIFY BY HAND
    part of 'dpi_resolution.dart';
    
    // **************************************************************************
    // JsonGenerator
    // **************************************************************************
    
    /// Maps a value of type [int] to an instance of [DpiResolution].
    /// Add the following getter to your class definition:
    /// ```
    /// static Map<int,DpiResolution> get valueMap => _$DpiResolutionValueMap;
    /// ```
    final _$DpiResolutionValueMap = Map<int, DpiResolution>.unmodifiable({
      DpiResolution.LOW.value: DpiResolution.LOW,
      DpiResolution.MEDIUM.value: DpiResolution.MEDIUM,
      DpiResolution.HIGH.value: DpiResolution.HIGH
    });
    
    /// Converts a map [Map<String, dynamic>] to an instance of [DpiResolution].
    /// Add the following factory constructor to your class definition:
    /// ```
    /// factory DpiResolution.fromJson(Map<String, dynamic> json) =>
    ///   _$DpiResolutionFromJson(json);
    /// ```
    DpiResolution _$DpiResolutionFromJson(Map<String, dynamic> json) {
      int value = GenericEnum.fromJson(json).value;
      DpiResolution instance = _$DpiResolutionValueMap[value];
      if (instance == null) {
        throw GenericEnumException(
          'Could not find DpiResolution instance with value: $value.',
        );
      }
      return instance;
    }
    

Features and bugs #

Please file feature requests and bugs at the issue tracker.

0.0.1 #

Initial Version of the library.

0.0.2 #

Added Travis badge.

0.0.3 #

Examples now include a generated function prefix.

0.0.4 #

Removed dependency on built_collection.

0.0.5 #

Updated dependency on generic_enum.

0.1.0 #

Added generic enum example with function: identifier().

0.1.1 #

Amended docs.

0.1.2 #

Updated dependencies.

example/README.md

Generic Enum Example #

Build Status

Introduction #

This library serves as a demonstrator on how to create generic_enum classes with features like json-serialization, a value-instance map, and access to instance identifiers.

Starting Point #

As a starting point, users could follow these steps:

  1. Clone this repository.
  2. Add you own generic enum classes to the local folder generic_enum/generic_enum_example/lib.
  3. In a terminal navigate to the local folder generic_enum/generic_enum_example and build the project by running the command:
    $ pub run build_runner build --delete-conflicting-outputs
    

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_example: ^0.1.2

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_example/direction.dart';
import 'package:generic_enum_example/direction.g.dart';
import 'package:generic_enum_example/dpi_resolution.dart';
import 'package:generic_enum_example/dpi_resolution.g.dart';
import 'package:generic_enum_example/name_part.dart';
import 'package:generic_enum_example/name_part.g.dart';
import 'package:generic_enum_example/plane_type.dart';
import 'package:generic_enum_example/plane_type.g.dart';
import 'package:generic_enum_example/vector.dart';
import 'package:generic_enum_example/vector.g.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
0
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]
50
Learn more about scoring.

We analyzed this package on Mar 31, 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
generic_enum ^0.1.7 0.1.9
generic_enum_annotation ^0.1.5 0.1.5
Transitive dependencies
json_annotation 3.0.1
Dev dependencies
build_runner ^1.0.0
generic_enum_builder ^0.1.8