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