lucperkins
lucperkins

Reputation: 808

Making a data type iterable within a Polymer element in Dart

I have a custom data type in Dart that I would like to make iterable using template repeat. Here are stripped-down versions of the data types in question:

class Note {
  String content;
  Note(this.content);
}

class Notebook {
  List<Note> notes;
  Notebook(this.notes);
}

I want to be able to iterate through the Notes in a Notebook like so:

<polymer-element name="x-notebook=view">
  <ul>
    <template repeat="{{note in notebook}}">
      <li is="x-note-view" note="{{note}}></li>
    </template>
  </ul>

  <script ...></script>
</polymer-element>

The problem, of course, is that standard Lists can be iterated through in this way, but I'm not sure how to modify my custom Notebook data type to do the same.

One way that does seem to work is to attach a toList() method to the Notebook class:

List<Note> toList() => notes;

But I was hoping to make this possible without first converting to a List.

Upvotes: 4

Views: 197

Answers (1)

Vyacheslav Egorov
Vyacheslav Egorov

Reputation: 10492

Reading the source of polymer_expression package reveals that the right side of the in operator has to be an Iterable, so you have to implement this interface.

I did a quick test and the following seems to work:

import 'dart:collection' show IterableMixin;

// [IterableMixin] implement all methods of [Iterable]
// in terms of [iterator].
class Notebook extends Object with IterableMixin<Note> {
  List<Note> notes;
  Notebook(this.notes);

  get iterator => notes.iterator;
}

Upvotes: 5

Related Questions