I faced a problem while try building an application.
the problem is that trying to set the field in SomeClass
with a general setField
function.
my implementation was like this but faced an issue withthis[fieldName]
;
EDITED
class TestClass {
String name; // <- to set this the memberName = 'name';
int age; // <- to set this the memberName = 'age';
// and both will use the same setField as setter.
TestClass({required name, required age});
// the prev code is correct and no problem with it.
/** the use will be like this to set the value of name **/
/** test.setField(memberName : 'name', valueOfThatMemberName: 'test name'); // notice here **/
/** the use will be like this to set the value of age **/
/** test.setField(memberName : 'age', valueOfThatMemberName: 15); // notice here **/
void setField({required String memberName, required var valueOfThatMemberName}) {
// some extra validation and logic,..
this[memberName] = valueOfThatMemberName; // this gives this error:
/** Error: The operator '[]=' isn't defined for the class 'TestClass'. **/
}
// this will return the valueOfThePassedMemberName;
getField({required String memberName}) {
return this[memberName]; // <= this gives this error
/** Error: The getter 'memberName' isn't defined for the class 'TestClass'. **/
}
}
void main() {
TestClass test = TestClass(name: 'alaa', age: 14);
/** here is the way to use it. **/
test.setField(memberName: 'name', valueOfThePassedMemberName: 'test name'); // notice here
test.setField(memberName: 'age', valueOfThePassedMemberName: 16); // notice here
print(test.getField(memberName: 'name')); // <- this should print the name of test object.
}
setting the values just through the setField method.
ADDING RUNABLE JS CODE
// i need to do the exact same thing here with the dart.
export class Entity {
constructor(data: {}) {
Object.keys(data).forEach(key => {
this.set(key, data[key], true);
});
}
get(field: string) {
return this["_" + field];
}
set(field: string, value: any, initial = false) {
this["_" + field] = value;
}
}
2
Answers
After a lot of researching, I found that there is no way to do it directly, but there is another way i'm gonna drive you into the steps:
1- Install the package
we need to install Reflectable
Readme Changelog Example Installing Versions Scores Use this package as a library Depend on it Run this command:
With Dart:
With Flutter:
2- Import the package into the class
3- Create the Reflectable Class
4- Add the Annotation into the class
6- build main.reflectable.dart
run this line in project root folder
7- Initialize the Refactable
import this line into the main.dart
add this line into your main.
8- Use it
Finally Thanks to who contribute to try to answer and help :-)