简体   繁体   中英

How do I get notified when something is added or removed from an observable list in Dart?

I have an observable list from Polymer and Dart. I want a getter to run when something is added or removed from the list. How do I do that?

My list:

final ObservableList masterList = toObservable([]);

My getter:

List get subList => masterList.where((item) => item.isDone);

When I add or remove from masterList , I want subList to update the view.

Use changes to listen for any changes to an observable object. You can put this into the created() lifecycle callback:

class Example extends PolymerElement with ObservableMixin {
  final ObservableList masterList = toObservable([]);
  created() {
    masterList.changes.listen((List<ChangeRecord> changes) {
      notifyProperty(this, const Symbol('subList'));
    }
  }

  List get subList => masterList.where((item) => item.isDone);
}

It's important to remember that changes is watching for additions and removals from the masterList . You probably don't want the typical bindProperty pattern because that just watches for changes to the variable itself (if the variable is set to a different object, then bindProperty will run).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM