问题描述
我想使用observe包,而不必在我的模型中有注释,只有通过在setters中提高notifyPropertyChange,所以测试我做了以下测试
I am trying to use the observe package without having to have annotations in my Model, and only by raising notifyPropertyChange in setters, so to test i made the following test
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,但是它从来不监听变化,任何想法为什么?
i am changing the value of a property in an instance of Model using a setter that raises notifyPropertyChange
but it never listens for changes, any idea why?
推荐答案
我想要使用 ChangeNotifier
而不是 Observable
。
我不确定 notifyPropertyChange
但是使用 Observable
,通常需要调用 dirtyCheck
可获得关于更改的通知。
I'm not sure about notifyPropertyChange
but with Observable
you normally need to call dirtyCheck
to get notified about changes.
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';
}
这篇关于从聚合物飞镖观察包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!