Skip to content

Create dart data classes easily, fast and without writing boilerplate or running code generation.

License

Notifications You must be signed in to change notification settings

arthurbcd/dart-data-class-tools

 
 

Repository files navigation

Dart Safe Data Class Generator

Create dart data classes easily, fast and without writing yourself or running code generation.

This fork adds new features:

  • Type Safety with ArgumentError or customizable input in settings.
  • Custom Serialization with comment-directives and in settings (custom.types).
  • Stricter immutability with @immutable annotation.
  • Custom header lines on generation. Add imports, labels, ignore annotations, comments, code, etc.

Type Safety

The commands are the same as before, but with cast<T> as a caster.


  factory Test.fromMap(Map<String, dynamic> map) {
    // throw any Error you would like in the `custom.argumentError` extension setting.
     T cast<T>(String k) => map[k] is T ? map[k] as T : throw ArgumentError.value(map[k], k); // <- customizable
    return Test(
      //primitives
      id: cast<int>('id'),
      name: cast<String>('name'),

      //primitive nullables
      name: cast<String?>('name'),
      isPremium: cast<bool?>('isPremium'),

      //default values
      members: List<String>.from(cast<Iterable?>('members') ?? const <String>[]),
      address: Map<String, dynamic>.from(cast<Map<String, dynamic>?>('address') ?? const {}),
      
      //custom
      icon: IconData(cast<int>('icon')),
      paymentType: Payment.values[cast<int>('paymentType')],
      date: DateTime.parse(cast<String>('date')),

      //custom nullables
      color: map['color'] != null ? Color(cast<int>('color')) : null,
      time: map['time'] != null ? cast<Timestamp>('time') : null,
    );
  }

Custom Header Lines

Add anything you would like in the header lines: labels, comments, imports, ignore annotaions, code, etc.

  // Generated by Dart Safe Data Class Generator. * Change this header on extension settings *
  // ignore_for_file: avoid_dynamic_calls, lines_longer_than_80_chars

  class Test {
   ... 
  }

Custom Serialization


To generate safe data classes with custom serialization using comment directives, follow these steps:

Option 1

Add custom type directives to fromMap and toMap directly in settings.

Example:

"dart-data-class-generator.custom.types": [
       {
        "type": "DateTime",
        "fromMap": "DateTime.parse(String)",
        "toMap": "toIso8601String()"
       },
       {
        "type": "Color",
        "fromMap": "Color(int)",
        "toMap": "value"
       },
       {
        "type": "IconData",
        "fromMap": "IconData(int)",
        "toMap": "codePoint"
       },
       {
        "type": "Timestamp", // to ignore serialization, or use `//ignore`
        "fromMap": "",
        "toMap": ""
       }
  //...others,
]

Opntion 2

Annotate the desired properties in your Dart class with comment directives in the following format:

final Type property; // fromCustom(Type ?? defaultValue), toCustom() // comments...

Where:

  • The Type is required.
  • The defaultValue is optional.
  • You can use either () or [].
  • Either from or to parts can be empty.
  • The toCustom part after the , and before // is simply copied.
  • Whitespaces and everything after the closing // is ignored.
// Examples.
final DateTime createdAt; // DateTime.parse(String), toIso8601String()
final MyFile file; // fromBytes(String), toBytes()
final String name; // fromInt(int)
final DateTime updatedAt; // , toTimestamp()
final EnumType type; // myCollection.values[double ?? 0xFF]

Tip: You can import custom methods from other files adding the imports in the header-lines section in settings.


Starting from this point, the README content below remains unmodified from the original fork.

Features

The generator can generate the constructor, copyWith, toMap, fromMap, toJson, fromJson, toString, operator == and hashCode methods for a class based on class properties or raw JSON.

Additionally the generator has a couple of useful quick fixes to speed up your development process. See the Additional Features Section for more.

If this extension is helpful to you, consider giving it a star on GitHub or leave a review on the Visual Studio Marketplace ❤️

Create Data Classes Based on Class Properties

Usage

You can generate data classes either by the quick fix dialog or by running a command. In the quick fix dialog you have the option to not only generate whole data classes but also only specific methods. The command has the advantage of being able to generate multiple classes at the same time.

Quick fix

  • Create a class with properties.
  • Place your cursor on the first line of the class, the constructor or a field.
  • Hit CTRL + . to open the quick fix dialog.
  • Choose one of the available options.

Command

  • Create a class with properties.
  • Hit CTRL + P to open the command dialog.
  • Search for Dart Data Class Generator: Generate from class properties and hit enter.
  • When there are multiple classes in the current file, choose the ones you'd like to create data classes of in the dialog.

It is also possible to run the generator on an existing data class (e.g. when some parameters changed). The generator will then try to find the changes and replace the class with its updated version. Note that custom changes to generated functions may be overridden.

You can also customize the generator for example to use Equatable for value equality. See the Settings section for more options.

Enums

In order for enums to be correctly serialized from and to JSON, please annotate them using a comment like so:

// enum
final Enum myEnum; // enum <- or here.

Usage with Equatable

Although using the generator is fast, it still doesn't spare you from all the boiler plate necessary, which can be visually distracting. To reduce the amount of boiler plate needed, the generator works with Equatable. Just extend the class with Equatable or mix with EquatableMixin and the generator will use Equatable for value equality.

You can also use the setting dart-data-class-generator.useEquatable, if you always want to use Equatable for value equality.

Create Data Classes Based on JSON (Beta)

Usage

  • Create an empty dart file.
  • Paste the raw JSON without modifying it into the otherwise empty file.
  • Hit CTRL + P to open the command dialog.
  • Search for Dart Data Class Generator: Generate from JSON and hit enter.
  • Type in a class name in the input dialog. This will be the name of the top level class if the JSON contains nested objects, all other class names will be inferred from the JSON keys.
  • When there are nested objects in the JSON, a dialog will be appear if you want to separate the classes into multiple files or if all classes should be in the same file.

Note: This feature is still in beta! Many API's return numbers like 0 or 1 as an integer and not as a double even when they otherwise are. Thus the generator may confuse a value that is usually a double as an int.

Additional Features

The extension includes some additional quick fixes that might be useful to you:

Import refactoring

Sort imports alphabetically and bring them into the correct format easily.

Settings

You can customize the generator to only generate the functions you want in your settings file.

  • dart-data-class-generator.json.key_format: Whether to use snake_case or camelCase for the json keys.
  • dart-data-class-generator.quick_fixes: If true, enables quick fixes to quickly generate data classes or specific methods only.
  • dart-data-class-generator.useEquatable: If true, uses Equatable for value equality and hashCode.
  • dart-data-class-generator.fromMap.default_values: If true, checks if a field is null when deserializing and provides a non-null default value.
  • dart-data-class-generator.constructor.default_values: If true, generates default values for the constructor.
  • dart-data-class-generator.constructor.required: If true, generates @required annotation for every constructor parameter. Note: The generator wont generate default values for the constructor if enabled!
  • dart-data-class-generator.json.separate: Whether to separate a JSON into multiple files, when the JSON contains nested objects. ask: choose manually every time, separate: always separate into multiple files, current_file: always insert all classes into the current file.
  • dart-data-class-generator.override.manual: If true, asks, when overriding a class (running the command on an existing class), for every single function/constructor that needs to be changed whether the generator should override the function or not. This allows you to preserve custom changes you made to the function/constructor that would be otherwise overwritten by the generator.
  • dart-data-class-generator.constructor.enabled: If true, generates a constructor for a data class.
  • dart-data-class-generator.copyWith.enabled: If true, generates a copyWith function for a data class.
  • dart-data-class-generator.toMap.enabled: If true, generates a toMap function for a data class.
  • dart-data-class-generator.fromMap.enabled: If true, generates a fromMap function for a data class.
  • dart-data-class-generator.toJson.enabled: If true, generates a toJson function for a data class.
  • dart-data-class-generator.fromJson.enabled: If true, generates a fromJson function for a data class.
  • dart-data-class-generator.toString.enabled: If true, generates a toString function for a data class.
  • dart-data-class-generator.equality.enabled: If true, generates an override of the == (equals) operator for a data class.
  • dart-data-class-generator.hashCode.enabled: If true, generates a hashCode function for a data class.
  • dart-data-class-generator.hashCode.use_jenkins: If true, uses the Jenkins SMI hash function instead of bitwise operator from dart:ui.

About

Create dart data classes easily, fast and without writing boilerplate or running code generation.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 92.1%
  • Dart 7.9%