我试图使用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实例中的属性值,但它从不会听取更改,不知道为什么?
答案 0 :(得分:2)
我认为您希望使用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';
}