2

I try to build an application in dart. I inject a service class in two other to share some data. The problem is now, I don't know how can i trigger an event(onChange) in one class by another class attribute change(async).

1 Answers1

7

You can either create a stream getter where others can listen to or use observable.

Stream:

import 'dart:async';

// custom event class
class MyEvent {
  String eventData;

  MyEvent(this.eventData);
}

// class that fires when something changes
class SomeClass {
  var changeController = new StreamController<MyEvent>();
  Stream<MyEvent> get onChange => changeController.stream;

  void doSomething() {
    // do the change
    changeController.add(new MyEvent('something changed'));
  }
}

// listen to changes
...
var c = new SomeClass();
c.onChange.listen((e) => print(e.eventData));
...

Observable: see
- Observe package from polymer dart
- How to use Dart ChangeNotifier class?
- http://www.dartdocs.org/documentation/observe/0.12.2/index.html

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567