felangel / equatable

A Dart package that helps to implement value based equality without needing to explicitly override == and hashCode.
https://pub.dev/packages/equatable
MIT License
901 stars 100 forks source link

fetch all list of properties dynamic #144

Closed ttpho closed 1 year ago

ttpho commented 1 year ago

Status

READY

Breaking Changes

NO

Description

current approach

class Person extends Equatable {
  const Person(this.name);

  final String? name;

  @override
  List<Object?> get props => [name];
}

When I implement props, I must do it manually.

If class Person has more than one attribute then I write a lot of code, I wonder is it possible to do it automatically?

new approach

class Person extends Equatable {
  const Person(this.name);

  final String? name;

  @override
  List<Object?> get props => fetchProperties();
}

I created method fetchProperties from EquatableExtension. The method will return all lists of properties dynamic.

The idea from this post, I use dart:mirrors library.

List<Object?> list = <Object?>[];
Object -> InstanceMirror -> ClassMirror -> declarations.values -> List<DeclarationMirror>
for v in  List<DeclarationMirror>
  v is VariableMirror
    filedValue <- v
    list.add(filedValue)

Note

The dart:mirrors library is unstable

Self test

class Person extends Equatable {
  const Person(this.name);

  final String? name;

  @override
  List<Object?> get props => fetchProperties();
}

class Group extends Equatable {
  const Group(this.persons);

  final List<Person> persons;

  @override
  List<Object?> get props => fetchProperties();
}

void main(List<String> arguments) {
  final Person person1 = Person("ttpho");
  final Person person2 = Person("ttpho");
  print(person1 == person1); // true
  print(person1 == person2); // true

  final Group group1 = Group([person1]);
  final Group group2 = Group([person2]);

  print(group1 == group1); // true
  print(group1 == group2); // true
}

Related PRs

Todos

Steps to Test or Reproduce

Impact to Remaining Code Base

ttpho commented 1 year ago

@felangel Thank you for your review.