Implement an Observer pattern in Dart

后端 未结 1 1757
北恋
北恋 2020-12-01 14:52

I would like to implement an observer pattern in Dart but I\'m not sure how to go about it.

Let\'s say I have a class:



        
相关标签:
1条回答
  • 2020-12-01 15:32

    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;
    
    }
    
    0 讨论(0)
提交回复
热议问题