简体   繁体   English

如何在 Flutter Dart 中同时使用 .sort 和 .toSet 方法

[英]How to use both .sort and .toSet methods together in Flutter Dart

List colour= ["peach","red","yellow","green","black"];列表颜色= [“桃”,“红色”,“黄色”,“绿色”,“黑色”];

//How to use both.sort and.toSet methods together in Flutter Dart. //如何在Flutter Dart中同时使用.sort和.toSet方法。

Sort method return type void so you can not use.toSet Method together. sort 方法的返回类型为 void,因此不能将 .toSet 方法一起使用。 But after applying sort you can use.toSet method it works as you expected但是在应用排序之后,您可以使用 .toSet 方法,它可以按预期工作

Try this尝试这个

List colour= ["peach","red","yellow","green","black"]; 
colour.sort((a, b) => a.length.compareTo(b.length));   
colour.toSet().toList();

Try this extension:试试这个扩展:

extension SortEX on List {
  List sortAndSet() {
    sort();
    return toSet().toList();
  }
}

the result you get:你得到的结果:

//[black, green, peach, red, yellow]

Sort the List first, then toSet()首先对List进行排序,然后toSet()

List colour= ["peach","red","yellow","green","black", "black"];

colour.sort();
var res = colour.toSet();
print(res); //{black, green, peach, red, yellow}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM