我正在尝试使用观察包,而无需在模型中添加注释,而只需在 setter 中引发notifyPropertyChange,因此为了测试我进行了以下测试
import 'package:observe/observe.dart';
import 'dart:async';
import 'dart:math';
void main() {
var dummyWatchingModel = new DummyWatchingModel();
new Timer.periodic(new Duration(milliseconds:1000), (_){
//calls a function that set a random value to the property in the observable model
dummyWatchingModel.setModelProps();
});
}
class Model extends Observable{
int _x;
Model(this._x);
int get x=> _x;
void set x(int value){
_x = notifyPropertyChange(#_x, _x, value);
}
}
class DummyWatchingModel{
Model model = new Model(1);
final rng = new Random();
anotherModel(){
//watch for changes in model instance properties
this.model.changes.listen((List<ChangeRecord> records) {
for(ChangeRecord change in records){
print(change.toString());
}
});
}
//the callback for the timer to assign a random value model.x
setModelProps(){
model.x = rng.nextInt(100);
print('called...');
}
}
我正在使用引发 notifyPropertyChange
的 setter 来更改 Model 实例中的属性值,但它从不监听更改,知道为什么吗?
最佳答案
我认为您想使用ChangeNotifier
而不是Observable
。
我不确定 notifyPropertyChange
,但对于 Observable
,您通常需要调用 dirtyCheck
来获取有关更改的通知。
我不久前做了一个小例子来了解这两者是如何工作的:
import 'package:observe/observe.dart';
class Notifiable extends Object with ChangeNotifier {
String _input = '';
@reflectable
get input => _input;
@reflectable
set input(val) {
_input = notifyPropertyChange(#input, _input, val + " new");
}
Notifiable() {
this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
}
}
class MyObservable extends Observable {
@observable
String counter = '';
MyObservable() {
this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
}
}
void main() {
var x = new MyObservable();
x.counter = "hallo";
Observable.dirtyCheck();
Notifiable notifiable = new Notifiable();
notifiable.input = 'xxx';
notifiable.input = 'yyy';
}
关于dart - 从聚合物 Dart 观察包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24276737/