Sorting ascending and descending in Dart?
For ascending
var nlist = [1, 6, 8, 2, 16, 0]
nlist.sort((a, b) => a.compareTo(b));
For descending
var nlist = [1, 6, 8, 2, 16, 0]
nlist.sort((b, a) => a.compareTo(b));
Another way to sort
var nlist = [4,2,1,5];
var ascending = nlist..sort();
var descending = ascending.reversed;
print(ascending); // [1, 2, 4, 5]
print(descending); // [5, 4, 2, 1]
For Ascending:
var nlist = [4,2,1,5]
var compare = (b, a) => a.compareTo(b);
For Descending:
var compare = (b, a) => -a.compareTo(b);
Would be interesting what you actually expected from happening after the change.
Compare returns +1
, 0
, -1
depending on whether the 2nd argument is greater than the 1st or 0
if they are equal. When you swap the two arguments +1
becomes -1
and vice versa this leads to a descending order instead of an ascending one.
1.compareTo(2)
returns -1
and
print(nlist.sort((a, b) => a.compareTo(b)));
prints the list elements in ascending order, so yes, ascending is default.