You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Dart中如何结合使用.sort与.toSet方法?

Flutter Dart中结合使用.sort与.toSet方法的实操说明

首先明确两个方法的核心作用:

  • .toSet():将List转换为Set集合,自动剔除重复元素(Set不允许存在重复项),之后需用.toList()转回List才能调用排序方法。
  • .sort():对List进行排序,默认按字符串字典序排列,也可自定义排序规则。

关键操作顺序:先去重,再排序

虽然Dart中List.toSet()返回的LinkedHashSet会保留插入顺序,但Set本质是无序集合,依赖该特性并不稳妥。因此最佳实践是先去重,再转List排序。

示例代码(基于你提供的列表,添加重复元素演示去重效果)

void main() {
  // 包含重复元素的颜色列表
  List<String> colour = ["peach","red","yellow","green","black", "red"];
  
  // 一步完成去重+排序:转Set去重→转回List→调用sort
  List<String> uniqueSortedColours = colour.toSet().toList()..sort();
  
  print(uniqueSortedColours); // 输出:[black, green, peach, red, yellow]
}

自定义排序规则

若不需要默认的字典序,可给.sort()传入比较函数,比如按字符串长度排序:

void main() {
  List<String> colour = ["peach","red","yellow","green","black", "red"];
  List<String> uniqueSortedColours = colour.toSet().toList();
  
  // 按字符串长度从小到大排序
  uniqueSortedColours.sort((a, b) => a.length.compareTo(b.length));
  
  print(uniqueSortedColours); // 输出:[red, black, peach, green, yellow]
}

内容的提问来源于stack exchange,提问作者Chintan Harkhani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 16:24:44