Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Map or a List observable in Web UI

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?

like image 711
Shailen Tuli Avatar asked Apr 04 '13 14:04

Shailen Tuli


1 Answers

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>
like image 161
Shailen Tuli Avatar answered Oct 01 '22 19:10

Shailen Tuli