Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
Seth Ladd Avatar asked Dec 10 '25 05:12

Seth Ladd


1 Answers

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).

like image 97
Seth Ladd Avatar answered Dec 13 '25 00:12

Seth Ladd