gpt4 book ai didi

dart - 如何在 Dart 中对 ObservableList 进行排序?

转载 作者:行者123 更新时间:2023-12-03 02:08:55 26 4
gpt4 key购买 nike

我似乎无法对 ObservableList<T> 进行排序并将排序反射(reflect)在我的 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这似乎也不起作用。这里有什么不正确的地方吗?

最佳答案

您的Person类需要使用compareTo方法而不是compare实现Comparable

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>

关于dart - 如何在 Dart 中对 ObservableList<T> 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21443969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com