data_class_annotation_generator 0.1.6 copy "data_class_annotation_generator: ^0.1.6" to clipboard
data_class_annotation_generator: ^0.1.6 copied to clipboard

outdated

Automatically generate equals, hashCode, toString and copyWith methods for @dataClass annotated classes.

DataClass #

How to use : #

Add this to your pubspec.yaml's dependency section :

data_class_annotation: any

And this to the dev_dependency section :

data_class_annotation_generator: any

What it does : #

This library provides the @dataClass annotation, used to generate :

  • equals
  • hashCode
  • toString
  • copyWith

For example, this (main.dart) :

@dataClass
class Model {
  final int id;
  final DateTime creationDate;
  final List<SubClass> subClass;

  Model(this.id, {this.creationDate, this.subClass});

  @override int get hashCode => dataHashCode;
  @override bool operator ==(other) => dataEquals(other);
  @override String toString() => dataToString();
}

@dataClass
class SubClass {
  final int id;

  SubClass(this.id);
  
  @override int get hashCode => dataHashCode;
  @override bool operator ==(other) => dataEquals(other);
  @override String toString() => dataToString();
}

Will generate this (main.g.dart) :

extension ModelExt on Model {
  Model copyWith({
    int id,
    DateTime creationDate,
    List subClass,
  }) {
    return Model(
      id ?? this.id,
      creationDate: creationDate ?? this.creationDate,
      subClass: subClass ?? this.subClass,
    );
  }

  bool dataEquals(dynamic other) =>
      other is Model &&
      this.id == other.id &&
      this.creationDate == other.creationDate &&
      this.subClass == other.subClass;

  String dataToString() =>
      "Model(id=${this.id}, creationDate=${this.creationDate}, subClass=${this.subClass})";

  int get dataHashCode =>
      (Model).hashCode ^
      this.id.hashCode ^
      this.creationDate.hashCode ^
      this.subClass.hashCode;
}

extension SubClassExt on SubClass {
  SubClass copyWith({
    int id,
  }) {
    return SubClass(
      id ?? this.id,
    );
  }

  bool dataEquals(dynamic other) => other is SubClass && this.id == other.id;

  String dataToString() => "SubClass(id=${this.id})";

  int get dataHashCode => (SubClass).hashCode ^ this.id.hashCode;
}

Keep in mind : #

To generate the copyWith method, data_class_annotation uses the first constructor defined in the @dataClass annotated class. If you want to use a specific constructor, just annotate it with the @primaryConstructor annotation

9
likes
0
pub points
0%
popularity

Publisher

unverified uploader

Automatically generate equals, hashCode, toString and copyWith methods for @dataClass annotated classes.

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

Dependencies

analyzer, build, build_config, code_builder, data_class_annotation, meta, source_gen

More

Packages that depend on data_class_annotation_generator