我试图使用observe包,而不必在模型中具有批注,而仅通过在 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';
}