How can I sort an ObservableList <T> in a Dart?
I cannot sort ObservableList<T>and have the view reflected in my Polymer element. Here is the definition of the selection item:
class PeopleElement extends PolymerElement {
ObservableList<Person> people = toObservable(new List<Person>());
PeopleElement.created() : super.created();
}
And here is the class definition Person:
class Person {
String name;
Person(this.name);
int compare(Person p) {
return name.compareTo(p.name);
}
}
Now I want to add a function sortto the class PeopleElement:
class PeopleElement extends PolymerElement {
...
ObservableList<Person> sortByName() {
people.sort((Person a, Person b) {
a.compare(b);
}
}
}
I also tried the above function as a return void, and that didn't work either. Does anything wrong here?
+4
1 answer
Your class Personshould implement Comparableusing a method compareToinsteadcompare
library people_element;
import 'dart:async';
import 'package:polymer/polymer.dart';
class Person implements Comparable{
String name;
Person(this.name);
@override
int compareTo(Person other) {
return name.compareTo(other.name);
}
}
@CustomTag('people-element')
class PeopleElement extends PolymerElement {
var people = toObservable(new List<Person>());
PeopleElement.created() : super.created() {
print('PeopleElement');
}
@override
void enteredView() {
people.add(new Person('c'));
people.add(new Person('a'));
people.add(new Person('f'));
people.add(new Person('b'));
super.enteredView();
new Timer(new Duration(seconds: 3), () => sortByName());
}
ObservableList<Person> sortByName() {
people.sort();
}
}
<polymer-element name="people-element">
<template>
<template repeat="{{p in people}}">
<p>{{p.name}}</p>
</template>
</template>
<script type="application/dart" src="people_element.dart"></script>
</polymer-element>
+3