Skip to content
Blog

Ordering Dart Lists: Sorting Mechanics, Custom Comparators, and Multi-Key Precedence

A complete guide to sorting lists in Dart: in-place vs immutable sorting, custom comparators with Comparable.compare, multi-field ordering, and stability.

Published on • December 5, 2026

AI Assistant

Sorting data is a universal task in application development: ordering items by price, sorting leaderboard participants by score, or arranging dates chronologically.

In Dart, the List.sort() method provides an efficient Dual-Pivot Quicksort implementation under the hood. However, understanding comparator signatures, stability caveats, and non-mutating sort patterns is essential to prevent subtle bugs.


The Comparator Contract

In Dart, ordering is determined by a Comparator<T> callback:

typedef Comparator<T> = int Function(T a, T b);

The comparator contract follows standard mathematical ordering rules:

  • Returns a negative integer (e.g. -1) if a < b (a appears before b).
  • Returns zero (0) if a == b.
  • Returns a positive integer (e.g. 1) if a > b (a appears after b).

In-Place Sorting with Comparable.compare

Types that implement Comparable (like int, double, String, DateTime) can be sorted with zero configuration or via Comparable.compare:

void main() {
  final numbers = [42, 7, 19, 3, 99];

  // 1. Natural ascending order (mutates original list)
  numbers.sort();
  print('Ascending: $numbers'); // [3, 7, 19, 42, 99]

  // 2. Descending order using inline comparator
  numbers.sort((a, b) => b.compareTo(a));
  print('Descending: $numbers'); // [99, 42, 19, 7, 3]

  // 3. String alphabetical sorting
  final names = ['Charlie', 'Alice', 'Bob'];
  names.sort(Comparable.compare);
  print('Names: $names'); // [Alice, Bob, Charlie]
}

Important: List.sort() mutates the list in-place. If your list is fixed-length or unmodifiable (such as const [...] or List.unmodifiable(...)), calling .sort() will throw an UnsupportedError.


Non-Mutating Sorting (Immutable Pattern)

In Flutter reactive architectures (BLoC, Riverpod, Provider), you should avoid mutating existing state collections directly. Create a copy before sorting:

// Idiomatic copy-and-sort in Dart:
final sortedList = [...originalList]..sort();

// Or using List.of:
final sortedList2 = List.of(originalList)..sort();

Custom Object Comparators

When sorting complex model objects, implement a custom comparator or have the class implement Comparable<T>:

class Product {
  final String name;
  final double price;
  final double rating;

  Product(this.name, this.price, this.rating);

  @override
  String toString() => '$name: \$$price ($rating★)';
}

void main() {
  final catalog = [
    Product('Laptop', 1200.0, 4.8),
    Product('Mouse', 25.0, 4.2),
    Product('Keyboard', 85.0, 4.6),
  ];

  // Sort by price ascending
  catalog.sort((a, b) => a.price.compareTo(b.price));
  print('By Price: $catalog');

  // Sort by rating descending (highest first)
  catalog.sort((a, b) => b.rating.compareTo(a.rating));
  print('By Rating: $catalog');
}

Multi-Field Ordering (Tie-Breaking)

A common requirement is sorting by one primary field, and falling back to a secondary field when the primary values are identical (e.g., sort employees by department, then by seniority):

class Employee {
  final String department;
  final int yearsOfService;
  final String name;

  Employee(this.department, this.yearsOfService, this.name);
}

int employeeComparator(Employee a, Employee b) {
  // 1. Primary sort: department alphabetically
  final deptCompare = a.department.compareTo(b.department);
  if (deptCompare != 0) return deptCompare;

  // 2. Secondary sort (tie-breaker): years of service descending
  final serviceCompare = b.yearsOfService.compareTo(a.yearsOfService);
  if (serviceCompare != 0) return serviceCompare;

  // 3. Tertiary sort: name alphabetically
  return a.name.compareTo(b.name);
}

Handling Null Values in Comparators

If your fields are nullable, explicit null handling prevents runtime crashes:

class Task {
  final String title;
  final DateTime? dueDate;
  Task(this.title, this.dueDate);
}

void sortTasksByDueDate(List<Task> tasks) {
  tasks.sort((a, b) {
    if (a.dueDate == null && b.dueDate == null) return 0;
    if (a.dueDate == null) return 1; // Put nulls at the end
    if (b.dueDate == null) return -1;
    return a.dueDate!.compareTo(b.dueDate!);
  });
}

Sort Stability Note

Dart’s List.sort() is not guaranteed to be stable (equal elements may swap their relative positions). If stability is required, combine the comparator with the original element index:

List<T> stableSort<T>(List<T> list, Comparator<T> compare) {
  final indexed = list.indexed.toList();
  indexed.sort((a, b) {
    final cmp = compare(a.$2, b.$2);
    return cmp != 0 ? cmp : a.$1.compareTo(b.$1);
  });
  return indexed.map((e) => e.$2).toList();
}

Summary

  • Use List.sort() for fast in-place Dual-Pivot Quicksort.
  • Use [...list]..sort() for immutable sorting in state management.
  • Chain comparisons (if (cmp != 0) return cmp;) to implement multi-level tie-breakers.
  • Explicitly guard null values when ordering nullable properties.