How to observe simple variable in dart language How to observe simple variable in dart language dart dart

How to observe simple variable in dart language


(This answer applies to Polymer.dart.)

The observe package includes a wrapper for single observable values: ObservableBox.

import 'package:observe/observe.dart';import 'dart:async';void main() {  ObservableBox myValue = new ObservableBox('hello');  myValue.changes.listen((List<ChangeRecord> records) {    PropertyChangeRecord record = records[0] as PropertyChangeRecord;    print('${record.field} changed, it is now ${myValue.value}');  });  new Timer.periodic(const Duration(seconds: 1), (t) {    myValue.value = new DateTime.now();  });}

There is no way to observe a top-level or function-scope single string, boolean, int, or double without using ObservableBox.

If the string, boolean, int, or double is a field of a class, you can use ObservableMixin and the @observable annotation.

class Foo extends Object with ObservableMixin {  @observable String bar = '';}

You can then get notified when an instance of Foo changes:

foo.changes.listen((List<ChangeRecord> records) {  // ...});


Here is an example of the binding of a string value that is object attribute:

<!DOCTYPE html><html>  <head>    <title>index</title>    <script src="packages/polymer/boot.js"></script>  </head>  <body>    <template id="_template" bind>      <input type="text" value="{{name}}">      <p>The name is {{name}}</p>    </template>    <script type="application/dart" src="index.dart"></script>  </body></html>
import 'dart:html';import 'package:polymer/polymer.dart';class Person extends Object with ObservableMixin {  @observable  String name;  Person(this.name);}main() {  query("#_template").model = new Person('Bob');}