I can make a String or a num type observable by using the @observable declaration in the Dart code:
@observable
var x = '';
and {{ }}
syntax in the html:
<div>x = {{x}}</div>
But @observable
does not work with Lists and Maps. How do I make those observable?
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 Map
objects have data added to them every second. With toObservable()
creating
the 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';
@observable
num 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>
来源:https://stackoverflow.com/questions/15814349/making-a-map-or-a-list-observable-in-web-ui