Making a Map or a List observable in Web UI

血红的双手。 提交于 2019-12-21 09:22:47

问题


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?


回答1:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!