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

StackOverflow https://stackoverflow.com/questions/18971387

  •  29-06-2022
  •  | 
  •  

Pregunta

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.

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top