2

let say I have a class like this

class Human {

   String name;
   int age;
   HairColor hairColor;

   static const int numberOfLegs = 2

}

as you can see I have 3 properties and 1 static property in Human class above, I want to get the number of class properties (without the static) of a class

so I need to get something like this

final john = Human(name: "John", age: 24, hairColor: HairColor.black)
print(john.length) // will print '3'

I need to programmatically get the number of properties of a class because I will use it in unit testing, because I create a method to convert that class to map, but If I add a new property, I often forget to add it to the method

Map<String, dynamic> toMap() {

   return {
      "name" : this.name,
      "age" : this.age
      "hairColor" : this.hairColor
      "newProperty" : "I often forget to add this new property in this method"
   }

}

I see an article to do something like this in here and also from SO in How do I get all fields for a class in Dart? , both of them using dart:mirrors , but it seems dart:mirrors is no longer available

Alexa289
  • 8,089
  • 10
  • 74
  • 178
  • "because I create a method to convert that class to map" - **don't do that**: writing entity-to-DTO mapping by-hand is error-prone and _tedious_ (and as a software-dev, your job is to _eliminate tedium!_), so here's a better idea: use `automap` instead: https://pub.dev/packages/automap – Dai Aug 16 '21 at 00:16
  • 3
    This isn't possible without reflection. Possibly [`package:reflectable`](https://pub.dev/packages/reflectable) can do it, but I'm not familiar with it. But if you're serializing to/from JSON, you really should be using code-generation instead (e.g. [`package:json_serializable`](https://pub.dev/packages/json_serializable), [`package:built_value`](https://pub.dev/packages/built_value)). – jamesdlin Aug 16 '21 at 00:23

0 Answers0