Implement an Observer pattern in Dart

Here’s a way to do it using the Observe package. The example is taken from code comments in that package (and adapted to your example above). Essentially, you annotate fields you want to be observable with the @observable annotation, and then listen for changes (which you trigger with the call to Observable.dirtyCheck();

First, add the observable package in your pubspec.yaml

dependencies:
  observe: any

Then create a quick test program…

import 'package:observe/observe.dart';

class MyClass extends Object with Observable {
  @observable String observedField = "Hello";

  toString() => observedField.toString(); 
}

main() {
  var obj = new MyClass();

  // anonymous function that executes when there are changes
  obj.changes.listen((records) {
    print('Changes to $obj were: $records');
  });


  obj.observedField = "Hello World";

  // No changes are delivered until we check for them
  Observable.dirtyCheck();

  print('done!');
}

This produces the following output:

Changes to Hello World were: [#<PropertyChangeRecord Symbol("observedField") from: Hello to: Hello World>]
done!

Update in response to comments…
Updating the example to omit the Observable.dirtyCheck() you can use a setter and notifyPropertyChanged, with the class instead mixing in ChangeNotifier

class MyClass2 extends Object with ChangeNotifier {

  String _observedField = "Hello";

  @reflectable get observedField    => _observedField;
  @reflectable set observedField(v) {
    _observedField = notifyPropertyChange(#observedField, _observedField, v);    
  }

  toString() => observedField;

}

Leave a Comment