简体   繁体   中英

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.

Sort method return type void so you can not use.toSet Method together. But after applying sort you can use.toSet method it works as you expected

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 colour= ["peach","red","yellow","green","black", "black"];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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