Я столкнулся с проблемой при попытке создать приложение.
проблема в том, что мы пытаемся установить поле в SomeClass
с помощью общей setField
функции.
моя реализация была такой, но столкнулась с проблемой this[fieldName]
;
ОТРЕДАКТИРОВАНО
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.
}
установка значений только через метод setField.
ДОБАВЛЕНИЕ РАБОЧЕГО JS-КОДА
// 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;
}
}
class TestClass {
late String fieldName;
late dynamic value;
TestClass({required fieldName, required value});
void setField({required String fieldName, required var value}) {
// some extra validation and logic,..
this.fieldName = fieldName;
this.value = value;
}
getField() {
return fieldName;
}
getValue() {
return value;
}
}
void main() {
TestClass test = TestClass(fieldName: 'name', value: 'Alaa');
test.setField(fieldName: 'name', value: 'Alaa');
print('${test.getField()}: ${test.getValue()} ');
test.setField(fieldName: 'age', value: 14);
print('${test.getField()}: ${test.getValue()} ');
}
спасибо за ваше время, но я думаю, вы упускаете момент, когда меняете имя поля на fieldName и пытаетесь действовать, моя проблема в том, что fieldName - это строка, я не знаю, имя это или возраст.
Повторно обновил мой ответ. Пожалуйста, сделайте вопрос более ясным. :)
извините за это, но вы меняете всю идею, `fieldName` не является членом TestClass. это имя-члена, и значение не является членом в TestClass, это значение этого имени-члена. я отредактирую свой вопрос, чтобы сделать его более ясным.
пожалуйста, проверьте отредактированную версию вопроса. я добавляю код из своего проекта js, и он имеет ту же логику, которую мне нужно реализовать в dart.
После долгих исследований я обнаружил, что нет способа сделать это напрямую, но есть другой способ, который я собираюсь ввести вас в шаги:
1- Установите пакет
нам нужно установить Reflectable
Прочти меня Список изменений Пример Установка Версии Результаты Используйте этот пакет в качестве библиотеки Зависеть от этого Запустите эту команду:
С Дартом:
dart pub add reflectable
С флаттером:
flutter pub add reflectable
2- Импортируйте пакет в класс
import 'package:reflectable/reflectable.dart';
3- Создайте отражаемый класс
class MyReflectable extends Reflectable {
const MyReflectable() : super(invokingCapability);
}
const myReflectable = MyReflectable();
4- Добавьте аннотацию в класс
@myReflectable
class TestClass {
late String name;
late int age;
setField({required String fieldName, value}) {
var instanceMirror = myReflectable.reflect(this);
instanceMirror.invokeSetter(fieldName, value);
}
getField({required String fieldName}) {
var instanceMirror = myReflectable.reflect(this);
return instanceMirror.invokeGetter(fieldName);
}
}
6- построить main.reflectable.dart
запустите эту строку в корневой папке проекта
dart run build_runner build
7- Инициализируйте Reactable
импортируйте эту строку в main.dart
import 'package:erp/main.reflectable.dart';
добавьте эту строку в свой main.
initializeReflectable();
8- Используйте это
TestClass test = TestClass();
test.setField(fieldName: 'name', value: 'Alaa');
test.getField(fieldName: 'name'); // <- this will return 'Alaa'
test.setField(fieldName: 'name', value: 'Ahmad');
test.getField(fieldName: 'name'); // <- this will return 'Ahmad'
// and the same for any other field.
test.setField(fieldName: 'age', value: 14);
test.getField(fieldName: 'age'); // <- this will return 14
test.setField(fieldName: 'age', value: 20);
test.getField(fieldName: 'age'); // <- this will return 20
Наконец-то Спасибо тем, кто вносит свой вклад, чтобы попытаться ответить и помочь :-)
установщик fieldName не определен для класса TestClass.