Making a Map or a List observable in Web UI
Use toObservable()
with the List or Map as an argument. This creates a binding between the List or Map object and its representation in the UI.
The following example uses toObservable()
. Notice that the List and Mapobjects have data added to them every second. With toObservable()
creatingthe proper binding, the UI for these objects auto-magically updates to show the added items.
When the List or Map are clear()
ed, the the UI once again reflects this.
For instructions on how to build and run a script such as this one, see http://www.dartlang.org/articles/web-ui/tools.html.
Here is the main.dart
file:
import 'dart:async';import 'package:web_ui/web_ui.dart';@observablenum x = 0; // @observable works fine with a number. List list = toObservable(new List());Map<String, num> map = toObservable(new Map());void main() { new Timer.periodic(new Duration(seconds: 1), (_) { x += 1; list.add(x); map[x.toString()] = x; if (x % 4 == 0) { list.clear(); map.clear(); } return x; });}
And here is the accompanying dart.html
file:
<!DOCTYPE html><html> <body> <p>x = {{ x }}</p> <ul> <template iterate='item in list'> <li>list item = {{item}}</li> </template> </ul> <ul> <template iterate='key in map.keys'> <li>map key = {{key}}, map value = {{map[key]}}</li> </template> </ul> <script type="application/dart" src="main.dart"></script> </body></html>