To sort the items of a set in Dart, you can convert the set to a list and then sort the list using the sort()
method.
In this example,
numbers
containing some integer elements using the Set
class.toList()
method.sort()
method.void main() {
Set<int> numbers = {5, 3, 1, 4, 2};
List<int> sortedNumbers = numbers.toList();
sortedNumbers.sort();
print('Sorted numbers:');
for (int number in sortedNumbers) {
print(number);
}
}
Sorted numbers: 1 2 3 4 5
In this example,
fruits
containing some string elements using the Set
class.toList()
method.sort()
method.void main() {
Set<String> fruits = {'Banana', 'Apple', 'Cherry', 'Date'};
List<String> sortedFruits = fruits.toList();
sortedFruits.sort();
print('Sorted fruits:');
for (String fruit in sortedFruits) {
print(fruit);
}
}
Sorted fruits: Apple Banana Cherry Date
In this tutorial, we learned How to Sort Items of a Set in Dart language with well detailed examples.