Open In App

Dart - Sort a List

Last Updated : 15 Jul, 2025
Suggest changes
Share
10 Likes
Like
Report

The List data type is similar to arrays in other programming languages. A list is used to represent a collection of objects. It is an ordered group of objects. The core libraries in Dart are responsible for the existence of the List class, its creation, and manipulation. Sorting of the list depends on the type of list we are sorting, i.e. if we are sorting an integer list then we can use a simple sort function whereas if it is a string list then we use compareTo to sort the list.

Two main data types are stored in List:

  • Integer Lists
  • String Lists

We will learn to sort both of them in the article below.

sort_in_dart


1. Sorting an Integer List

An integer list can be sorted by the simple sort function.

Example:

Dart
// Main function void main() {  // Creating List  List<int> geeksforgeeks = [13, 2, -11, 142, -389, 32, 3032, 0];    // Sorting List  geeksforgeeks.sort();    // Printing Sorted List  print(geeksforgeeks); } 

Output:

[-389, -11, 0, 2, 13, 32, 142, 3032]

2. Sorting a String List

The string is sorted by comparing the length in the sort function.

- Comparing the length

Example:

Dart
// Main function void main() {  // Creating list of string  List<String> geeksforgeeks = ['one', 'two', 'three', 'four'];    // Sorting string by comparing the length  geeksforgeeks.sort((a, b) => a.length.compareTo(b.length));    // Printing the list  print(geeksforgeeks); } 

Output:

[one, two, four, three]


If we use sort without comparing the length, then:

- Without comparing the length

Example:

Dart
// Main function main() {  // Creating list of string  List<String> geeksforgeeks = ['one', 'two', 'three', 'four'];    // Sorting string without  // comparing the length  geeksforgeeks.sort();    // Printing the list  print(geeksforgeeks); } 

Output:

[four, one, three, two]


Using the cascades method while sorting

Example:

Dart
// Main function void main() {  // Creating list of string  List<int> geeksforgeeks = [13, 2, -11, 142, -389, 0];    // Sorting string and Printing the list  print(geeksforgeeks..sort()); } 

Output:

[-389, -11, 0, 2, 13, 142]



Article Tags :

Explore