我正在尝试创建一个可以动态设置对象属性的函数,如下所示:
void main() {
final obj = Item();
obj.update(5);
print(obj.xVal);
}
class ObjectBase {
void _setData(current, newValue) {
current = newValue;
print(current);
}
}
class Item extends ObjectBase {
int _x;
int get xVal => _x;
update(x) {
_setData(_x, x);
}
}
_setData
中的print语句可以正常工作,但即使传递了_x,它实际上也似乎不会更改_x。我希望更改此处的引用将在任何地方进行更新。那么,为什么这不起作用,并且有修复程序?
您可以假设我确实有充分的理由在
_setData
中调用update
,而不仅仅是在update
中实现功能。更新:
我想要达到的现实生活中的例子
class ViewModel extends ChangeNotifier {
void _setDataFromDependency(current, newValue) {
if (!deepDynamicEquality(current, newValue)) {
current = newValue;
notifyListeners();
}
}
}
class ListScreenViewModel extends ViewModel {
int _localCount = 0;
List<int> _globalList;
ListScreenViewModel();
List<int> get globalList => _globalList;
int get localCount => _localCount;
incrementLocal() {
_localCount++;
notifyListeners();
}
void update(ListStore listStore) {
_setDataFromDependency(_globalList, listStore.globalList);
// if (!deepDynamicEquality(_globalList, listStore.globalList)) {
// _globalList = listStore.globalList;
// notifyListeners();
// }
}
}
最佳答案
过度简化的解决方法是return
从_setData
值。 @ julemand101已经回答了限制。
class ObjectBase {
int _setData(current, newValue) {
current = newValue;
print('current: $current');
return current;
}
}
class Item extends ObjectBase {
int _x;
int get xVal => _x;
update(x) {
_x = _setData(_x, x);
}
}
关于flutter - 为什么不能在嵌套函数内设置动态属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62360101/