Sort Lists Dart & Flutter: 5 Sort Examples Dart

In this article we’ll take a look at how to sort lists in Dart (and Flutter as well) in this post, which is a typical activity that you’ll encounter in the vast majority of your projects. The examples are arranged in order of difficulty, from simple to sophisticated, and cover the majority of real-life circumstances.

Sorting a List of Numbers In Dart

We may easily sort a list of numbers in ascending or descending order by using the sort() function. This function manipulates the original list rather than returning a new one.

void main() {
  List<double> myNumbers = [1, 2.5, 3, 4, -3, 5.4, 7];
  myNumbers.sort();
  print('Ascending order: $myNumbers');
  print('Descending order ${myNumbers.reversed}');
}Code language: PHP (php)

Output:

Ascending order: [-3.0, 1.0, 2.5, 3.0, 4.0, 5.4, 7.0]
Descending order (7.0, 5.4, 4.0, 3.0, 2.5, 1.0, -3.0)Code language: CSS (css)

Sorting a List of Strings In Dart

This is a similar case to the first. To sort the string members in a list in alphabetical order, we utilize the sort() function (from A to Z or from Z to A).

void main() {
  List<String> myFruits = [
    'apple',
    'coconut',
    'banana',
    'strawberry',
    'water melon',
    'pear',
    'plum'
  ];
  myFruits.sort();
  print('Ascending order (A to Z): $myFruits');
  print('Descending order (Z to A): ${myFruits.reversed}');
}Code language: PHP (php)

Output:

Ascending order (A to Z): [apple, banana, coconut, pear, plum, strawberry, water melon]
Descending order (Z to A): (water melon, strawberry, plum, pear, coconut, banana, apple)Code language: CSS (css)

Sorting a List of Maps In Dart

Sorting a list of maps is little more difficult. We’ll need to employ the compareTo() and sort() methods.
A list of fake items is sorted in ascending and decreasing order of sale price in the tiny program below.

void main() {
  List<Map<String, dynamic>> myProducts = [
    {"name": "Shoes", "price": 100},
    {"name": "Pants", "price": 50},
    {"name": "Book", "price": 10},
    {"name": "Lamp", "price": 40},
    {"name": "Fan", "price": 200}
  ];

  // Selling price from low to high
  myProducts.sort((a, b) => a["price"].compareTo(b["price"]));
  print('Low to hight in price: $myProducts');

  // Selling price from high to low
  myProducts.sort((a, b) => b["price"].compareTo(a["price"]));
  print('High to low in price: $myProducts');
}Code language: JavaScript (javascript)

Output:

Low to hight in price: [{name: Book, price: 10}, {name: Lamp, price: 40}, {name: Pants, price: 50}, {name: Shoes, price: 100}, {name: Fan, price: 200}]

High to low in price: [{name: Fan, price: 200}, {name: Shoes, price: 100}, {name: Pants, price: 50}, {name: Lamp, price: 40}, {name: Book, price: 10}]Code language: CSS (css)

Sorting a List of Objects In Dart

The sort() and compareTo() methods may be used to sort a list of objects by their property values, much like they can sort a list of maps.

Let’s imagine you’ve grown a user base and want to categorize them by age. The program listed below will assist you.

class User {
  String name;
  int age;

  User(this.name, this.age);

  @override
  toString() {
    return ('$name - $age years old \n');
  }
}

void main() {
  List<User> users = [
    User('Plumber', 10),
    User('John Doe', 50),
    User('Pipi', 4),
    User('Invisible Man', 31),
    User('Electric Man', 34)
  ];

  // Age from small to large
  users.sort((a, b) => a.age.compareTo(b.age));
  print('Age ascending order: ${users.toString()}');

  // Age from large to small
  users.sort((a, b) => b.age.compareTo(a.age));
  print('Age descending order: ${users.toString()}');
}Code language: JavaScript (javascript)

Output:

Age ascending order: [Pipi - 4 years old 
, Plumber - 10 years old 
, Invisible Man - 31 years old 
, Electric Man - 34 years old 
, John Doe - 50 years old 
]
Age descending order: [John Doe - 50 years old 
, Electric Man - 34 years old 
, Invisible Man - 31 years old 
, Plumber - 10 years old 
, Pipi - 4 years old 
]

Sorting a List using the Comparable abstract class In Dart

This example follows the same steps as the last one, but uses a different approach. We override the compareTo() function in the Comparable abstract class. The User class now contains the sorting logic.

class User extends Comparable {
  String name;
  int age;

  User(this.name, this.age);

  @override
  toString() {
    return ('$name - $age years old \n');
  }

  @override
  int compareTo(other) {
    // age < other.age
    if (age < other.age) {
      return -1;
    }

    // age > other.age
    if (age > other.age) {
      return 1;
    }

    // age == other.age
    return 0;
  }
}

void main() {
  List<User> users = [
    User('Plumber', 10),
    User('John Doe', 50),
    User('Pipi', 4),
    User('Invisible Man', 31),
    User('Electric Man', 34)
  ];

  // Age from small to large
  users.sort();
  print('Age ascending order: ${users.toString()}');
}Code language: JavaScript (javascript)

Output:

Age ascending order: [Pipi - 4 years old 
, Plumber - 10 years old 
, Invisible Man - 31 years old 
, Electric Man - 34 years old 
, John Doe - 50 years old 

The benefit of this method is that you don’t have to redo the sort algorithm as often, but the disadvantage is that it might make your code more complicated and redundant.

Conclusion

Dart contains powerful features built-in to the language to help you sort items and objects efficiently. Utilising the proper sorting technique, can reduce the development time required to produce your Flutter application, and also make the app more performant.

In this article, we took a look at several ways to sort lists in Dart & Flutter. Now you should feel at ease dealing with problems related to sorting numbers, strings, maps, and objects In Dart. As always, If you have found this article useful do not forget to share it and leave a comment if you have any questions. Happy Coding 🙂

Comments

Leave a Reply