Ho appena trascorso un po 'di tempo cercando di fare la stessa cosa. Come indicato nella risposta sopra, non è possibile utilizzare l'annotazione @observable
senza WebUI/Polymer. È comunque possibile utilizzare il pacchetto osservabile. Ecco un rapido esempio:
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);
}
Gli eventi sono asincrone quindi fate attenzione se si fa affidamento su l'ordine di questi eventi. L'output del programma di cui sopra è
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!