Enum extendable - Dart code generator. Generates enum extensions code.

Overview

Generates code for the extension on an enum.

Overview

Being able to add fields and methods to an enum.

Let's say we have the following enum:

enum MathOperator { plus, minus, multiply, divide }

It would be handy to use the enum values such as instances of some regular Dart class.
For example,

final n1 = 1;
final n2 = 2.0;
MathOperator.values.forEach((operator) {
  print('$n1 ${operator.symbol} $n2 = ${operator.calculate(n1, n2)}');
});

An extension on the enum will help us with it.

Extensions can give us even more.
We can get a specific enum item from the instance of a Dart class, for example in such way:

final MathOperator? mathOperator = "+".toNullableMathOperatorFromSymbol();


We can do it with collections as well:

final List<MathOperator?> mathOperators = ['+', '*'].toNullableMathOperatorFromSymbol();


All these extensions can be generated by these package.

Usage

Install

First, add build_runner and EnumExtendable to the pubspec.yaml file:

# pubspec.yaml
dependencies:
  enum_extendable_annotation:

dev_dependencies:
  build_runner:
  enum_extendable_generator:

And install them:

# Dart
pub get

# Flutter
flutter packages get

Packages:

  • build_runner, the tool to run code-generators;
  • enum_extendable_generator, the code generator;
  • enum_extendable_annotation, a package containing annotations for enum_extendable_generator.

Create a PODO (Plain Old Data Object) class and add annotations

Next, we need to create a PODO class to describe properties of the enum.
For example,

@ExtendableEnum()
enum MathOperator { plus, minus, multiply, divide }

@ExtendableEnumPodo()
class _MathOperatorPodo {
  final String symbol;
  final num Function(num, num) calculate;

  _MathOperatorPodo({
    required this.symbol,
    required this.calculate,
  });

  @ExtendableEnumValues()
  static final Map<MathOperator, _MathOperatorPodo> _values = {
    MathOperator.plus: _MathOperatorPodo(
      symbol: "+",
      calculate: (n1, n2) => n1 + n2,
    ),
    MathOperator.minus: _MathOperatorPodo(
      symbol: "-",
      calculate: (n1, n2) => n1 - n2,
    ),
    MathOperator.multiply: _MathOperatorPodo(
      symbol: "*",
      calculate: (n1, n2) => n1 * n2,
    ),
    MathOperator.divide: _MathOperatorPodo(
      symbol: "/",

      ///division by 0 will yield double.infinity
      calculate: (n1, n2) => n1 / n2,
    ),
  };
}

There are properties of an enum item that we want

  final String symbol;
  final num Function(num, num) calculate;

and a PODO object instance for each enum item in the Map<MathOperator, _MathOperatorPodo> values.

Three annotations are used here:

  • the enum annotation - @ExtendableEnum();
  • the PODO class annotation - @ExtendableEnumPodo();
  • the values map annotation - @ExtendableEnumValues().

Run the generator

  • If your package depends on Flutter:
    • flutter pub run build_runner build
  • If your package does not depend on Flutter:
    • dart pub run build_runner build

EnumExtendable will need us to both import the annotation and use the part keyword on the top of your files.

So, a file that wants to use EnumExtendable should start with:

import 'package:enum_extendable_annotation/enum_extendable_annotation.dart';

part 'example.enum_extendable.g.dart';

Note: If there is any collection field in the PODO object, one more import needs to be added (to compare collections correctly):

import 'package:collection/collection.dart';

Features

Extensions

Let's take the MathOperator enum as an example to explore available extensions.

@ExtendableEnum()
enum MathOperator { plus, minus, multiply, divide }

@ExtendableEnumPodo()
class _MathOperatorPodo {
  final String symbol;
  final num Function(num, num) calculate;

@ExtendableEnumValues()
  static final Map<MathOperator, _MathOperatorPodo> _values = {
    ...
  };

1. Extension on enum

This package generates an extension on enum for all fields of the PODO class.

extension MathOperatorExt on MathOperator {
  String get symbol {
    _checkMathOperatorValues();
    return _MathOperatorPodo._values[this]!.symbol;
  }

  num Function(num, num) get calculate {
    _checkMathOperatorValues();
    return _MathOperatorPodo._values[this]!.calculate;
  }
}

2. Extensions on classes of the PODO fields types

If we need to get a specific enum item by the value of some field of the PODO class

final MathOperator? mathOperator = "+".toNullableMathOperatorFromSymbol();

then we can use the generated class extension:

extension MathOperatorStringExt on String {
  MathOperator? toNullableMathOperatorFromSymbol() {
    _checkMathOperatorValues();
    for (MathOperator element in _MathOperatorPodo._values.keys) {
      if (_MathOperatorPodo._values[element]!.symbol == this) {
        return element;
      }
    }
    return null;
  }

  MathOperator toMathOperatorFromSymbol(
    MathOperator defaultValue,
  ) {
    _checkMathOperatorValues();
    for (MathOperator element in _MathOperatorPodo._values.keys) {
      if (_MathOperatorPodo._values[element]!.symbol == this) {
        return element;
      }
    }
    return defaultValue;
  }
}

3. Extensions on Iterable

Finally, similar extensions will be generated for Iterable.

extension MathOperatorStringIterableExt on Iterable<String> {
  List<MathOperator?> toNullableMathOperatorFromSymbol() {
    _checkMathOperatorValues();
    return List<MathOperator?>.of(
        map((e) => e.toNullableMathOperatorFromSymbol()).toList());
  }

  List<MathOperator> toMathOperatorFromSymbol(
    MathOperator defaultValue,
  ) {
    _checkMathOperatorValues();
    return List<MathOperator>.of(map((e) => e.toMathOperatorFromSymbol(
          defaultValue,
        )).toList());
  }
}

Such extensions allow us to map an iterable to a list of the enum items:

final List<MathOperator?> mathOperators = ['+', '*'].toNullableMathOperatorFromSymbol();

Annotations

ExtendableEnum

The enum should be annotated with ExtendableEnum.
It's a mandatory annotation.

ExtendableEnumPodo

Use 'ExtendableEnumPodo' to annotate the PODO class of your enum.' It's the second mandatory annotation.

ExtendableEnumValues

The map of values (PODO instances by enum values) should be annotated with ExtendableEnumValues.
This annotation can be omitted, if the name of this field is values.
There is one parameter bool checkCompleteness. If the value of this parameter is true an assert statement is generated to make sure that all enum items are in the values map. It can be useful when a new item is added into the enum.
The default value of checkCompleteness is true.

ExtendableEnumField

Any field of the PODO class can be annotated with ExtendableEnumField. This annotation is optional and can be used to determinate extensions nomenclature. It has two parameters:

  • bool enumExtension - set false if you don't want to generate a method for this field at the extension on enum.
    The default value is true.
  • bool classExtension - set false if you don't want to generate methods for a class (and Iterable of this class) of this field.
    The default value is true.
You might also like...

Various extensions on BuildContext to access inherited widget's state

context_extentions Getting inherited widget's state var themeData = context.theme; var scaffold = context.scaffold; var navigator = context.navi

Sep 23, 2021

Material io ext - A collection of extensions for creating widgets following material.io guidelines

material_io_ext It is a collection of extensions for creating widgets following

Jan 28, 2022

Package provides light widgets [for Linkify, Clean] and extensions for strings that contain bad words/URLs/links/emails/phone numbers

Package provides light widgets [for Linkify, Clean] and extensions for strings that contain bad words/URLs/links/emails/phone numbers

Package provides light widgets [for Linkify, Clean] and extensions for strings that contain bad words/URLs/links/emails/phone numbers

Oct 2, 2022

Dart code generator for helping with (firebase) analytics.

analytics_events_gen An easy generator for tracking firebase analytics events via type safe methods. Add to pubspec.yaml Check pub for the latest vers

Nov 16, 2022

A convenient code generator for app styleguide, gallery, wireframes and/or storyboard.

A convenient code generator for app styleguide, gallery, wireframes and/or storyboard.

Framy A convenient code generator for app styleguide, gallery, wireframes and/or storyboard. πŸ‘‰ Official documentation πŸ‘ˆ Packages In order to use Fra

Dec 19, 2022

The Swift code generator for your assets, storyboards, Localizable.strings, … β€” Get rid of all String-based APIs!

The Swift code generator for your assets, storyboards, Localizable.strings, … β€” Get rid of all String-based APIs!

SwiftGen SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them ty

Dec 31, 2022

bq Scanner : An QR Code and Barcode Scanner and Generator.

bq Scanner A Barcode Scanner. A QR Code Scanner. A Barcode Generator. A QR Code Generator. Visit bq Scanner at https://ritikpatle.github.io/bqscanner/

Jun 5, 2022

Adobe XD Flutter Code Generator - Plugin

Adobe XD Flutter Code Generator - Plugin

Dec 28, 2022

Code generator for Flutter's theme extension classes.

Code generator for Flutter's theme extension classes.

Welcome to Theme Tailor, a code generator and theming utility for supercharging Flutter ThemeExtension classes introduced in Flutter 3.0! The generato

Jan 2, 2023
Owner
null
Immutable value types, enum classes, and serialization.

Built Values for Dart Introduction Built Value provides: Immutable value types; EnumClass, classes that behave like enums; JSON serialization. Immutab

Google 816 Dec 23, 2022
Startup-Name-Generator-App-in-Flutter - Business Startup Name Generator App in Flutter

Business Startup Name Generator App #About APP: A simple mobile app that generat

AHSAN SIDDZ 0 Jan 30, 2022
The Reactive Extensions for Dart

RxDart About RxDart extends the capabilities of Dart Streams and StreamControllers. Dart comes with a very decent Streams API out-of-the-box; rather t

ReactiveX 3.2k Dec 20, 2022
Functional extensions to Dart collections.

collection_ext A set of extension methods for Dart collections, designed for the purpose of making it easier to write concise, functional-programming-

Yingxin Wu 7 Nov 21, 2022
Extensions and principles for modern Dart development.

neodart Neo-Dart, or "new" Dart, is a series of recommended packages and principles that break out of classic conventions ("we've always done it that

Neo Dart 10 Dec 6, 2022
A tool which automatically generates Flutter localization resources from CSV and Excel files.

flappy_translator A tool which automatically generates Flutter localization resources from CSV and Excel files. This is especially useful as any team

Smart&Soft 55 Sep 15, 2022
πŸ“² Flutter application that uses CycleGAN to generates an anime version from a selfie.

This application allows you to capture a picture of yourself or upload an existing image, then using Cycle-Consistent Adversarial Network (CycleGAN) t

null 3 Jun 19, 2022
Generates a new Flutter app with http client, theme, routing and localization features.

Starter Template Generates a new Flutter app with http client, theme, routing and localization features. Brick Uses: dio as http client pretty_dio_log

Cem AvcΔ± 12 Nov 3, 2022
🎯 This library automatically generates object classes from JSON files that can be parsed by the freezed library.

The Most Powerful Way to Automatically Generate Model Objects from JSON Files ⚑ 1. Guide ?? 1.1. Features ?? 1.1.1. From 1.1.2. To 1.2. Getting Starte

KATO, Shinya / εŠ θ—€ 真也 14 Nov 9, 2022
Awesome Flutter extensions to remove boilerplate

Awesome Flutter Extensions Awesome flutter extensions to remove boilerplate Installation Install using the Terminal: flutter pub add awesome_flutter_e

Alexandru Mariuti 3 Aug 20, 2022