Sorting Techniques in Flutter (Dart)

Sorting is a fundamental operation in programming, allowing you to arrange data in a meaningful order. Dart provides various techniques to sort data, each suitable for specific scenarios.

1.Sorting Lists with the sort() Method

The sort() method is the most common way to sort a list in Dart. It modifies the list in place based on a comparison function.

Example: Sorting by Integer Values

dartCopy codevoid main() {
  List<int> numbers = [3, 1, 4, 1, 5, 9];
  numbers.sort(); // Ascending order
  print(numbers); // Output: [1, 1, 3, 4, 5, 9]
}

Example: Sorting by String Values

dartCopy codevoid main() {
  List<String> names = ['Alice', 'Charlie', 'Bob'];
  names.sort();
  print(names); // Output: [Alice, Bob, Charlie]
}

2. Custom Sorting with sort()

You can pass a custom comparator to the sort() method to define your sorting logic.

Example: Sorting by Length of Strings

dartCopy codevoid main() {
  List<String> words = ['apple', 'banana', 'kiwi'];
  words.sort((a, b) => a.length.compareTo(b.length));
  print(words); // Output: [kiwi, apple, banana]
}

3. Creating a New Sorted List

To avoid modifying the original list, you can create a new sorted list using the List.from() or toList() methods.

Example: Creating a Sorted Copy

dartCopy codevoid main() {
  List<int> numbers = [3, 1, 4, 1, 5, 9];
  List<int> sortedNumbers = List.from(numbers)..sort();
  print(sortedNumbers); // Output: [1, 1, 3, 4, 5, 9]
}

4. Sorting Using Iterable and toList()

When working with collections that are not lists, such as Set or Iterable, convert them to a list and sort.

Example: Sorting a Set

dartCopy codevoid main() {
  Set<int> numbers = {9, 1, 4, 3};
  List<int> sortedNumbers = numbers.toList()..sort();
  print(sortedNumbers); // Output: [1, 3, 4, 9]
}

5. Sorting Maps

Dart does not support directly sorting maps, but you can sort their keys or values and reconstruct the map.

Example: Sorting by Keys

dartCopy codevoid main() {
  Map<String, int> scores = {'Alice': 90, 'Bob': 85, 'Charlie': 95};
  var sortedKeys = scores.keys.toList()..sort();
  var sortedMap = {for (var key in sortedKeys) key: scores[key]!};
  print(sortedMap); // Output: {Alice: 90, Bob: 85, Charlie: 95}
}

Example: Sorting by Values

dartCopy codevoid main() {
  Map<String, int> scores = {'Alice': 90, 'Bob': 85, 'Charlie': 95};
  var sortedEntries = scores.entries.toList()
    ..sort((a, b) => a.value.compareTo(b.value));
  var sortedMap = {for (var entry in sortedEntries) entry.key: entry.value};
  print(sortedMap); // Output: {Bob: 85, Alice: 90, Charlie: 95}
}

6. Sorting Using Functional Programming

Using Dart’s functional methods like map, where, and reduce, you can achieve sorting for more complex cases.

Example: Sorting Complex Objects

dartCopy codeclass Person {
  String name;
  int age;

  Person(this.name, this.age);
}

void main() {
  List<Person> people = [
    Person('Alice', 30),
    Person('Bob', 25),
    Person('Charlie', 35)
  ];

  people.sort((a, b) => a.age.compareTo(b.age));
  for (var person in people) {
    print('${person.name}, ${person.age}');
  }
  // Output:
  // Bob, 25
  // Alice, 30
  // Charlie, 35
}

7. Sorting Streams

For sorting data received as a Stream, collect the data first, then sort.

Example: Sorting Stream Data

dartCopy codeimport 'dart:async';

void main() async {
  Stream<int> numberStream = Stream.fromIterable([5, 3, 8, 1]);
  List<int> sortedNumbers = await numberStream.toList()..sort();
  print(sortedNumbers); // Output: [1, 3, 5, 8]
}

Sort a list of objects in Flutter (Dart) by property value

To sort a list of objects in Flutter (Dart) by a specific property, you can use the sort() method of the List class. The sort() method takes a comparison function as an argument to define the sorting logic.

Example:

Suppose you have a list of objects with the following Person class:

dartCopy codeclass Person {
  String name;
  int age;

  Person(this.name, this.age);

  @override
  String toString() => 'Person(name: $name, age: $age)';
}

To sort a list of Person objects by the age property:

dartCopy codevoid main() {
  List<Person> people = [
    Person('Alice', 30),
    Person('Bob', 25),
    Person('Charlie', 35),
  ];

  // Sort by age in ascending order
  people.sort((a, b) => a.age.compareTo(b.age));
  print('Sorted by age (ascending): $people');

  // Sort by age in descending order
  people.sort((a, b) => b.age.compareTo(a.age));
  print('Sorted by age (descending): $people');

  // Sort by name alphabetically
  people.sort((a, b) => a.name.compareTo(b.name));
  print('Sorted by name: $people');
}

Explanation:

  1. Ascending Order: Use a.property.compareTo(b.property).
  2. Descending Order: Use b.property.compareTo(a.property).
  3. Alphabetical Sorting: Works similarly for String properties.

Output:

Sorted by age (ascending): [Person(name: Bob, age: 25), Person(name: Alice, age: 30), Person(name: Charlie, age: 35)]
Sorted by age (descending): [Person(name: Charlie, age: 35), Person(name: Alice, age: 30), Person(name: Bob, age: 25)]
Sorted by name: [Person(name: Alice, age: 30), Person(name: Bob, age: 25), Person(name: Charlie, age: 35)]

This approach works efficiently for sorting by any property value.

FAQs about Sorting in Dart

Q1. How do I sort a list in descending order?

Use the custom comparator b.compareTo(a).

dartCopy codenumbers.sort((a, b) => b.compareTo(a));

Q2. Can I sort a list of nullable values?

Yes, but you must handle null values explicitly in the comparator.

dartCopy codevoid main() {
  List<int?> numbers = [3, null, 1, 4];
  numbers.sort((a, b) => (a ?? 0).compareTo(b ?? 0));
  print(numbers); // Output: [null, 1, 3, 4]
}

Q3. What happens if the list is empty?

The sort() method does nothing, and no error is thrown.

Q4. How efficient is sorting in Dart?

Dart uses the quicksort algorithm for small lists and mergesort for larger ones. Both are efficient for most cases.

Q5. Can I sort by multiple properties?

Yes, chain the comparison logic.

dartCopy codepeople.sort((a, b) {
  int result = a.age.compareTo(b.age);
  if (result == 0) {
    result = a.name.compareTo(b.name);
  }
  return result;
});

By mastering these techniques, you can effectively sort data in various formats and scenarios in Flutter and Dart!

Check Also : How to get Element at specific Index from List in Dart

Check Also : Geolocator Package in flutter : How to implement it

Read more updates related to flutter at flutterfever.com.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More