{"id":18521754,"url":"https://github.com/simphotonics/generic_enum","last_synced_at":"2025-04-09T09:33:23.234Z","repository":{"id":56831080,"uuid":"234162909","full_name":"simphotonics/generic_enum","owner":"simphotonics","description":"Dart enumerations with extension-methods offering json-serialization and a mapping of each enum instance to a const value with arbitrary data-type.","archived":false,"fork":false,"pushed_at":"2021-06-28T21:45:50.000Z","size":451,"stargazers_count":5,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-24T04:43:24.995Z","etag":null,"topics":["constant","dart","enumeration","extension-methods","generic-enums","generic-types","json-serialization"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/generic_enum","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/simphotonics.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-01-15T20:04:37.000Z","updated_at":"2024-04-05T05:24:21.000Z","dependencies_parsed_at":"2022-08-28T20:10:25.996Z","dependency_job_id":null,"html_url":"https://github.com/simphotonics/generic_enum","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fgeneric_enum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fgeneric_enum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fgeneric_enum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fgeneric_enum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/simphotonics","download_url":"https://codeload.github.com/simphotonics/generic_enum/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247792880,"owners_count":20996891,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["constant","dart","enumeration","extension-methods","generic-enums","generic-types","json-serialization"],"created_at":"2024-11-06T17:27:27.848Z","updated_at":"2025-04-09T09:33:22.316Z","avatar_url":"https://github.com/simphotonics.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Generic Enumerations For Dart\n[![Dart](https://github.com/simphotonics/generic_enum/actions/workflows/dart.yml/badge.svg)](https://github.com/simphotonics/generic_enum/actions/workflows/dart.yml)\n\n\n\n## Introduction\n\nEnumerations are ideal when we want to model *choosing* from a limited set of constant values.\nIn Dart, the value of an `enum` instance resolves to a `String`.\n\nThe package [`generic_enum`][generic_enum] can be used together with\n[`generic_enum_builder`][generic_enum_builder] to build extensions\nsupporting:\n* mapping of enum instances to a value of arbitrary data-type,\n* json-serialization.\n\n\n## Usage\n\nTo use this library include [`generic_enum`][generic_enum] as\ndependencies in your `pubspec.yaml` file.\nInclude [`generic_enum_builder`][generic_enum_builder],\nand [`build_runner`][build_runner] as dev_dependencies.\n\nThe example below shows how to define the enumeration `DpiResolution`\nand map each enum instance to a value of type `double`.\n\u003cdetails\u003e \u003csummary\u003e Click to show source code. \u003c/summary\u003e\n\n```Dart\n import 'package:generic_enum/generic_enum.dart';\n // 0. Import package exception_templates.\n import 'package:exception_templates/exception_templates.dart';\n\n // 1. Add a part statement pointing to the generated file.\n part 'dpi_resolution.g.dart';\n\n // 2. Define an enumeration\n //    and annotate it with @GenerateJsonExtension().\n @GenerateValueExtension(\n   valueType: double,\n   values: const {'90.0', '300.0', '600.0'},\n )\n @GenerateJsonExtension()\n enum DpiResolution { low , medium, high }\n\n```\n\u003c/details\u003e\n\nThe required steps are detailed below:\n\n0. Add the import directives shown above.\n1. Add a part statement referencing the generated file `dpi_resolution.g.dart`.\n2. Define an enumeration and annotate it with:\n   * @GenerateValueExtension() to generated the enum getters `value`, `valueMap` and `stringValue`\n   * @GenerateJsonExtension()  to generate the enum method `toJson()` and `To\u003cEnumName\u003e.fromJson(json)`.\n3. Configure the build targets (and amend the generate_for entry).\n   In your local `build.yaml` file add configurations for the builders\n   provided by the package [generic_enum_builder].\n\n   \u003cdetails\u003e  \u003csummary\u003e Click to show file content. \u003c/summary\u003e\n\n    ```sh\n      targets:\n        $default:\n          builders:\n            # Configure the builder `pkg_name|builder_name`\n            generic_enum_builder|extension_builder:\n              # Only run this builder on the specified input.\n              enabled: true\n              generate_for:\n                - lib/*.dart\n\n    ```\n   \u003c/details\u003e\n\n   Note: The file `dpi_resolution.dart` should be an asset that can be resolved by the builder.\n   To limit the number of files scanned for annotationed classes during\n   the build process one can use a `generate_for` statement in the builder configuration.\n\n4. Build the project by navigating to the project root directory and running the command:\n   ```Console\n   $ dart run build_runner build --delete-conflicting-outputs\n   ```\n5. For the example presented here, the build process will generate the file `dpi_resolution.g.dart`.\n    \u003cdetails\u003e  \u003csummary\u003e Click to show file content. \u003c/summary\u003e\n\n    ```Dart\n     // GENERATED CODE - DO NOT MODIFY BY HAND\n\n     part of 'dpi_resolution.dart';\n\n     // **************************************************************************\n     // ValueGenerator\n     // **************************************************************************\n\n     /// Extension on `DpiResolution` providing value-getters.\n     extension DpiResolutionValue on DpiResolution {\n       /// Returns a map of type `Map\u003cdouble, DpiResolution\u003e` mapping\n       /// each declared enum value to an instance of `DpiResolution`.\n       double get value =\u003e const \u003cDpiResolution, double\u003e{\n             DpiResolution.low: 90.0,\n             DpiResolution.medium: 300.0,\n             DpiResolution.high: 600.0,\n           }[this]!;\n\n       /// Returns the String identifier of an instance of `DpiResolution`.\n       String get stringValue =\u003e const \u003cDpiResolution, String\u003e{\n             DpiResolution.low: 'low',\n             DpiResolution.medium: 'medium',\n             DpiResolution.high: 'high',\n           }[this]!;\n\n       /// Returns a mapping of instance name to enum instance.\n       Map\u003cString, DpiResolution\u003e get valueMap =\u003e const \u003cString, DpiResolution\u003e{\n             'low': DpiResolution.low,\n             'medium': DpiResolution.medium,\n             'high': DpiResolution.high,\n           };\n     }\n\n     // **************************************************************************\n     // JsonGenerator\n     // **************************************************************************\n\n     /// Extension providing the functions `fromJson()`, `toJson()`,\n     /// and the getter `jsonEncoded`.\n     extension ToDpiResolution on DpiResolution {\n       /// Converts [json] to an instance of `DpiResolution`.\n       static DpiResolution fromJson(Map\u003cString, dynamic\u003e json) {\n         final index = (json['index']) as int?;\n         if (index == null) {\n           throw ErrorOf\u003cDpiResolution\u003e(\n               message: 'Error deserializing json to DpiResolution.',\n               invalidState: 'json[index] returned null.',\n               expectedState: 'A map entry: {index: int value}.');\n         }\n         if (index \u003e= 0 \u0026\u0026 index \u003c DpiResolution.values.length) {\n           return DpiResolution.values[index];\n         } else {\n           throw ErrorOf\u003cDpiResolution\u003e(\n               message: 'Function fromJson could not find '\n                   'an instance of type DpiResolution.',\n               invalidState: 'DpiResolution.values[$index] out of bounds.');\n         }\n       }\n\n       /// Converts `this` to a map `Map\u003cString, dynamic\u003e`.\n       Map\u003cString, dynamic\u003e toJson() =\u003e\n           {'index': DpiResolution.values.indexOf(this)};\n\n       /// Converts `this` to a json encoded `String`.\n       String get jsonEncoded =\u003e '{\"index\":${DpiResolution.values.indexOf(this)}}';\n     }\n    ```\n     \u003c/details\u003e\n\n## Enum - Value Mapping\n\nThe annotation [`@GenerateValueExtension`][GenerateValueExtension] requires the following parameters:\n* `Type valueType`: The type of the constants mapped to the enum instances.\n* `Set\u003cString\u003e values`. The entries are copied verbatim\nby the generator and must represent valid const instances of the data-type `valueType`. The number of\nentries must match the number of enum instances.\n\n\n## Limitations\n\nBecause of this [issue][issue] it is not possible to pass an instance of `enum`\nto the function `jsonEncode(Object object)` (provided by `dart:convert`)\neven if the function `toJson()` is defined in an extension on the `enum`.\n\nAlternative ways to serialize an instance of enum are:\n* Use the generated getter `toJsonEncoded` to retrieve a json encoded `String`.\n* Pass the result of `toJson()` to `jsonEncode`.\n* Use a full blown serialization approach like [`json_serializable`][json_serializable].\nThis is recommended if your project already uses [`json_serializable`][json_serializable].\n\nWhen it comes to deserialization, the usual approach is to define a factory constructor named `fromJson`.\nThis is not possible since extensions do not support constructors. Moreover, static extension-methods\nare accessed by specifying the extension name.\n\nTo keep the notation similar to the \"usual approach\", the extension containing the static method `fromJson`\nis named **To** + **Enum Name**, see example below.\n```Dart\nimport 'dart:convert';\nimport 'package:test/test.dart';\n\nimport 'dpi_resolution.dart';\n\n// The enum instance.\nfinal low = DpiResolution.low;\n\n// Encoding to Map\u003cString, dynamic\u003e.\n// Returns: {'index': 0}\nMap\u003cString, dynamic\u003e json = low.toJson();\n\n// Encoding to String.\nString jsonEncoded0 = jsonEncode(low);   // Throws error! Extensions not available for dynamic types.\nString jsonEncoded1 = jsonEncode(json)   // Using dart:convert.\nString jsonEncoded2 = low.jsonEncoded;   // Using the generated getter.\nexpect(jsonEncoded1, jsonEncoded2);\n\n// Decoding (notice the prefix \"To\").\nexpect(ToDpiResolution.fromJson(json), low);\nexpect(ToDpiResolution.fromJson(jsonDecode(jsonEncoded1)), low);\n```\n\n\n## Examples\n\nFurther examples on how to define and build generic enumeration classes can be found in the package [generic_enum_example].\n\n\n## Features and bugs\n\nPlease file feature requests and bugs at the [issue tracker].\n\n[issue tracker]: https://github.com/simphotonics/generic_enum/issues\n\n[analyzer]: https://pub.dev/packages/analyzer\n\n[build_runner]: https://pub.dev/packages/build_runner\n\n[extension-methods]: https://dart.dev/guides/language/extension-methods\n\n[GenerateValueExtension]: https://pub.dev/documentation/generic_enum/latest/generic_enum/GenerateValueExtension-class.html\n\n[generic_enum]: https://pub.dev/packages/generic_enum\n\n[generic_enum_annotation]: https://pub.dev/packages/generic_enum_annotation\n\n[generic_enum_example]: https://github.com/simphotonics/generic_enum/tree/main/generic_enum_example\n\n[generic_enum_builder]: https://pub.dev/packages/generic_enum_builder\n\n[json_serializable]: https://pub.dev/packages/json_serializable\n\n[source_gen]: https://pub.dev/packages/source_gen\n\n[issue]: https://github.com/dart-lang/sdk/issues/42742\n\n[issue comment]: https://github.com/dart-lang/language/issues/158#issuecomment-603967738","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimphotonics%2Fgeneric_enum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsimphotonics%2Fgeneric_enum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimphotonics%2Fgeneric_enum/lists"}