Is there any package to generate any dart class with exact method by passing class name and property on the fly by running another class?
For example: the class name is "Student" and it's properties are id, name, age etc.
`class Student {
String id;
String name;
int age;
String get id {
return id;
}
String get name {
return name;
}
int get age {
return age;
}
void set id(String id) {
this.id = id;
}
void set name(String name) {
this.name = name;
}
void set age(int age) {
if(age<= 0) {
print("Age should be greater than 5");
} else {
this.age = age;
}
}
}
I want to generate code something like that Student class. I want to generate it dynamically so that I can able to generate multiple class by providing class name and properties with method name. `
I tried to use build_runner, build_config to generate code but it's not dynamic. I had to write the code same code to generate the exact code.
CodePudding user response:
If you use Visual Studio Code you can use the
There is also Dart Data Class Generator, which allows you to generate things like json
serialization and ==
methods for your classes with your fields alredy set.
CodePudding user response:
No, it is not possible. The set of classes in your Dart program is fixed. Only those defined in the source code and imported libraries can be used.
The closest you can come to a class with dynamically specified fields and methods is to define a class that overrides the noSuchMethod method of Object. Instances of this class can look at their dynamic data and decide how to respond to a method call, based on the name of the called method. In this way, different instances of this class can pretend to support different methods and fields, based on their instance data.
What is the problem you are trying to solve using dynamically constructed classes? There may be a better way to solve your problem.