我有模型
class Model {
int counter;
}
现在我在运行时得到一个模型对象,所以我将它标记为动态的。
dynamic model = new Model();
int counter = 3;
什么是可能的方式做等同于
model['counter'] = counter;
需要提及的是模型中的计数器在应用中的某处使用,因此 tree shaking 不会将其删除。
我正在寻找任何解决方案。
class Model {
int counter;
var counterPath = "any way to reference counter field, so I can give the value to it";
}
对任何建议或黑客开放 :)
最佳答案
一种方法是实现字符串名称和实际字段之间的映射
class Model {
int counter;
// reading: print(model['counter']);
operator [](String name) {
switch(name) {
case 'counter':
return counter;
default: throw 'Field $name doesn't exist' in $runtimeType';
}
// writing: model['counter'] = counter;
operator []=(String name, dynamic value) {
switch(name) {
case 'counter':
counter = value;
break;
default: throw 'Field $name doesn't exist' in $runtimeType';
}
}
关于dart - 如何在没有 Dart 的情况下指向 Dart 中的字段 :mirrors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49115157/