sort method

  1. @override
void sort([
  1. int compare(
    1. T a,
    2. T b
    )?
])
override

Sorts this list according to the order specified by the compare function.

The compare function must act as a Comparator.

final numbers = <String>['two', 'three', 'four'];
// Sort from shortest to longest.
numbers.sort((a, b) => a.length.compareTo(b.length));
print(numbers); // [two, four, three]

The default List implementations use Comparable.compare if compare is omitted.

final numbers = <int>[13, 2, -11, 0];
numbers.sort();
print(numbers); // [-11, 0, 2, 13]

In that case, the elements of the list must be Comparable to each other.

A Comparator may compare objects as equal (return zero), even if they are distinct objects. The sort function is not guaranteed to be stable, so distinct objects that compare as equal may occur in any order in the result:

final numbers = <String>['one', 'two', 'three', 'four'];
numbers.sort((a, b) => a.length.compareTo(b.length));
print(numbers); // [one, two, four, three] OR [two, one, four, three]

Implementation

@override
void sort([int Function(T a, T b)? compare]) {
  _context.conditionallyRunInAction(() {
    if (_list.isNotEmpty) {
      final oldList = _list.toList(growable: false);
      _list.sort(compare);
      final changes = <ElementChange<T>>[];
      for (var i = 0; i < _list.length; ++i) {
        final oldValue = oldList[i];
        final newValue = _list[i];
        if (newValue != oldValue) {
          changes.add(ElementChange(
              index: i, oldValue: oldValue, newValue: newValue));
        }
      }
      if (changes.isNotEmpty) {
        _notifyElementsUpdate(changes);
      }
    }
  }, _atom);
}