Sort List by alphabetical order

List.sort((a, b) => a.toString().compareTo(b.toString()));

The above code code works, but if you use the above code, it will show capital letters first. That's why you have to convert them all to lowercase inside the sort extension.

List.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));

I found the best way to sort a list alphabetically is this:

      List.sort((a, b) => a.toString().compareTo(b.toString()));

< and > is usually a shortcut to a compareTo method.

just use that method instead.

data.sort((a, b) {
  return a['name'].toLowerCase().compareTo(b['name'].toLowerCase());
});

Thanks to Remi's answer, I extracted this as a Function.

typedef Sort = int Function(dynamic a, dynamic b);
typedef SortF = Sort Function(String sortField);

SortF alphabetic = (String sortField) => (a, b){
  return a[sortField].toLowerCase().compareTo(b[sortField].toLowerCase());
};

SortF number = (String sortField) => (a, b) {
      return a[sortField].compareTo(b[sortField]);
    };

with this you can write.

list.sort(alphabetic('name')); //replace name with field name

list.sort(number('name')); //replace name with field name

Tags:

Flutter