我只是花了一些时间尝试做同样的事情。如上面的答案所述,您不能在@observable
没有 WebUI/Polymer 的情况下使用注释。但是,您可以使用 observable 包。这是一个简单的例子:
import 'package:observe/observe.dart';
void main() {
var person = new Person(18, false);
person.changes.listen((List<ChangeRecord> changes) {
changes.forEach((PropertyChangeRecord change) {
print("$change");
});
});
person.changes.listen((List<ChangeRecord> changes) {
changes.where((PropertyChangeRecord c) => c.name == #employed).forEach((PropertyChangeRecord change) {
print("Employment status changed!");
});
});
print("start changing");
person.age = 19;
person.age = 19;
person.age = 19;
person.age = 20;
person.employed = true;
person.age = 21;
person.age = 22;
print("finish changing");
}
class Person extends ChangeNotifier {
int _age;
int get age => _age;
void set age (int val) {
_age = notifyPropertyChange(#age, _age, val);
}
bool _employed;
bool get employed => _employed;
void set employed (bool val) {
_employed = notifyPropertyChange(#employed, _employed, val);
}
Person(this._age, this._employed);
}
这些事件是异步的,因此如果您依赖这些事件的顺序,请小心。上述程序的输出是
start changing
finish changing
#<PropertyChangeRecord Symbol("age") from: 18 to: 19>
#<PropertyChangeRecord Symbol("age") from: 19 to: 20>
#<PropertyChangeRecord Symbol("employed") from: false to: true>
#<PropertyChangeRecord Symbol("age") from: 20 to: 21>
#<PropertyChangeRecord Symbol("age") from: 21 to: 22>
Employment status changed!