Functionality in parent class needs to detect changes to child class properties

后端 未结 1 1839
陌清茗
陌清茗 2021-01-21 16:56

I am trying to find a way for this parent \"Persistent\" class to add functionality so that the \"changed\" property becomes true whenever any property of the child object is ch

相关标签:
1条回答
  • 2021-01-21 17:26

    You can use the ChangeNotifier class like shown in the answers to this question

    • Observe package from polymer dart
    • How to use Dart ChangeNotifier class?
      see also
    • https://api.dartlang.org/apidocs/channels/be/dartdoc-viewer/observe/observe.ChangeNotifier
    • https://api.dartlang.org/apidocs/channels/be/dartdoc-viewer/observe/observe.Observable

    Another attempt is to use reflection but this is discouraged especially in the browser. The above solution uses reflection too but as far as I know the Smoke transformer generates code that replaces the reflective code when you run pub build.

    edit

    Only after a call to Observable.dirtyCheck(); a change detection is initiated (for all observable instances).

    import 'package:observe/observe.dart';
    
    class Persistent extends Observable {
      bool changed = false;
    
      Persistent() : super() {
        changes.listen((e) => changed = true);
      }
    }
    
    class Child extends Persistent {
      @observable num number = 1;
    }
    
    main() {
      Child item = new Child();
      item.number = 2;
      Observable.dirtyCheck();
      assert(item.changed == true);
    }
    
    0 讨论(0)
提交回复
热议问题