按以 dart 中的搜索字符串开头的名称对列表中的对象进行排序

sort objects in a list by names which starts with the search string in dart

假设我们有一个名为Thing的class,其定义如下:

class Thing {
   final int id;
   final String name;

   Thing(this.id, this.name);
}

我们有一个这样的 class 列表:

final List<Thing> things= [
   Thing(1, 'Black Car'),
   Thing(2, 'Red Car'),
   Thing(3, 'Car'),
   Thing(4, 'Green Car'),
   Thing(5, 'Car Yellow'),
   Thing(6, 'Car Blue'),
];

现在我们要使用 Car 一词在此列表中搜索某些内容,如下所示:

things.where(
    (thing) => thing.name.contains('Car')
    ).toList()

结果将是:

[
   Thing(1, 'Black Car'),
   Thing(2, 'Red Car'),
   Thing(3, 'Car'),
   Thing(4, 'Green Car'),
   Thing(5, 'Car Yellow'),
   Thing(6, 'Car Blue'),
]

现在如何根据名称以搜索词 Car 开头的事物对结果进行排序,换句话说,我希望这是结果:

   [
       Thing(3, 'Car'),
       Thing(5, 'Car Yellow'),
       Thing(6, 'Car Blue'),
       Thing(2, 'Red Car'),
       Thing(1, 'Black Car'),
       Thing(4, 'Green Car'),
    ]

提前致谢。

使用 List.sort,当事物以“Car”开头时,您优先考虑:

final filteredThings = things.where(
  (thing) => thing.name.contains('Car')
).toList();

filteredThings.sort((a, b) {
  if (a.startsWith('Car') && !b.startsWith('Car')) {
    return 1;
  }
  if (b.startsWith('Car') && !a.startsWith('Car')) {
    return -1;
  }
  return a.name.compareTo(b.name);
});

您可以根据需要使用排序功能对列表进行排序。这是一个工作示例:

class Thing {
  final int id;
  final String name;

  Thing(this.id, this.name);

  Map toJson() {
    Map data = {};
    data['id'] = id;
    data['name'] = name;
    return data;
  }
}

final List<Thing> things = [
  Thing(1, 'Black Car'),
  Thing(2, 'Red Car'),
  Thing(3, 'Car'),
  Thing(4, 'Green Car'),
  Thing(5, 'Car Yellow'),
  Thing(6, 'Car Blue'),
];

void main() async {
  List<Thing> myList =
      things.where((thing) => thing.name.contains('Car')).toList();
  myList
    ..sort((Thing a, Thing b) {
      int indexOfCarInA = a.name.indexOf('Car');
      int indexOfCarInB = b.name.indexOf('Car');
      if (indexOfCarInA < indexOfCarInB)
        return -1;
      else if (indexOfCarInA == indexOfCarInB) if (a.id <= b.id) return -1;
      return 1;
    });
  myList.forEach((element) {
    print(element.toJson());
  });

}