【问题标题】:Sort a List<object> by two properties one in ascending and the other in descending order in dart按 dart 中的两个属性对 List<object> 进行排序,一个按升序,另一个按降序
【发布时间】:2020-04-24 07:36:09
【问题描述】:

我看到了一些例子,我可以使用 flutter(dart) 中的一个属性对 dart 中的列表进行排序。

但是我怎样才能实现 SQL 查询所喜欢的功能,例如: 按点 desc,时间 asc 排序

【问题讨论】:

  • List.sort() 方法采用可选的 compare 函数 - 使用它来比较项目 - 但您也可以在数据类中实现 Comparable
  • 当我只使用 List.sort 时,我能够仅使用一个属性对其进行排序。实施可比较就成功了。谢谢!

标签: sorting flutter dart


【解决方案1】:

您可以对列表进行排序,然后重新排序..

这是我从 dartpad.dev 制作的示例

void main() {

  Object x = Object(name: 'Helloabc', i: 1);
  Object y = Object(name: 'Othello', i: 3);
  Object z = Object(name: 'Avatar', i: 2);

  List<Object> _objects = [
      x, y, z
  ];

 _objects.sort((a, b) => a.name.length.compareTo(b.name.length));

/// second sorting
//   _objects.sort((a, b) => a.i.compareTo(b.i));

  for (Object a in _objects) {
    print(a.name);
  }
}

class Object {
  final String name;
  final int i;

  Object({this.name, this.i});
}

【讨论】:

  • List.sort不是稳定的排序,因此不应期望第二个排序保留第一个排序的排序。对于稳定的排序,您应该改用 package:collection 中的 mergeSort 之类的东西。
  • @Pol ,我尝试在排序列表上再次使用排序。当我这样做时,我会失去第一类。
【解决方案2】:

我能够找到答案。感谢@pskink 和网址 https://www.woolha.com/tutorials/dart-sorting-list-with-comparator-and-comparable.

我实现了 Comparable 以按两个属性排序。

    class Sample implements Comparable<Sample> {
  final int points;
  final int timeInSeconds;
  Sample(
      {
      this.points,
      this.timeInSeconds});

  @override
  int compareTo(Sample other) {
    int pointDifference = points- other.points;
    return pointDifference != 0
        ? pointDifference 
        : other.timeInSeconds.compareTo(this.timeInSeconds);
  }
}

sampleList.sort();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-02-12
    • 1970-01-01
    相关资源
    最近更新 更多