如何在Dart中对ObservableList <t>进行排序?</t>

时间:2014-01-29 22:24:25

标签: dart observable dart-polymer polymer

我似乎无法对ObservableList<T>进行排序,并且在我的Polymer元素中反映了这种排序。这是一个示例元素定义:

class PeopleElement extends PolymerElement {
  ObservableList<Person> people = toObservable(new List<Person>());

  PeopleElement.created() : super.created();
}

以下是Person类的定义:

class Person {
  String name;
  Person(this.name);

  int compare(Person p) {
    return name.compareTo(p.name);
  }
}

现在,我想在sort类中添加PeopleElement函数:

class PeopleElement extends PolymerElement {
  ...

  ObservableList<Person> sortByName() {
    people.sort((Person a, Person b) {
      a.compare(b);
    }
  }
}

我还尝试将上述函数作为返回void,但似乎也没有用。有什么事情在这里跳出来是不正确的吗?

1 个答案:

答案 0 :(得分:3)

您的Person课程需要使用方法Comparable而不是compareTo来实施compare

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>