我试图为这个父类“持久”类寻找一种添加功能的方法,以便当子对象的任何属性被更改时,“已更改”属性变为真。
class Persistent {
bool changed = false;
Persistent() {
print('Something should be added here to make this work.');
}
}
class Child extends Persistent {
num number = 1;
// Nothing should be done in this class to make this work.
}
main() {
Child item = new Child();
item.number = 2;
assert(item.changed == true); //fails
}要求:我们的目标是让孩子的课程变得透明。检测更改的功能不能存在于子类中,只能存在于持久类中。
感谢各位省道专家的帮助!我期待着您的回音。
下面是正在进行中的工作,以实现这一工作:
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:observe/observe.dart';
class Persistent extends Object with ChangeNotifier {
bool changed = false;
Persistent() {
this.changes.listen((List<ChangeRecord> record) => changed = false);
//this.changes.listen((List<ChangeRecord> record) => changed = true); //Same exception
}
}
class Child extends Persistent {
@observable num number = 1;
// Nothing should be done in this class to make this work.
}
main() {
Child item = new Child();
item.number = 2;
assert(item.changed == true);
}上述情况给了我以下例外:
Unhandled exception:
'file:///home/david/Dropbox/WebDevelopment/DODB/source/DODB/bin/dodb.dart': Failed assertion: line 22 pos 10: 'item.changed == true' is not true.
#0 main (file:///home/david/Dropbox/WebDevelopment/DODB/source/DODB/bin/dodb.dart:22:10)
#1 _startIsolate.isolateStartHandler (dart:isolate-patch/isolate_patch.dart:216)
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:124)发布于 2014-08-04 04:30:48
您可以使用这个问题的答案中所示的ChangeNotifier类
另一种尝试是使用反射,但这是不鼓励的,特别是在浏览器中。上面的解决方案也使用反射,但据我所知,烟雾转换器生成的代码将在运行pub build时取代反射代码。
编辑
只有在调用Observable.dirtyCheck();之后,才会启动更改检测(对于所有可观察到的实例)。
import 'package:observe/observe.dart';
class Persistent extends Observable {
bool changed = false;
Persistent() : super() {
changes.listen((e) => changed = true);
}
}
class Child extends Persistent {
@observable num number = 1;
}
main() {
Child item = new Child();
item.number = 2;
Observable.dirtyCheck();
assert(item.changed == true);
}https://stackoverflow.com/questions/25111714
复制相似问题