flutter

Sort List by alphabetical order


I'm trying to sort a list by alphabetical order and tried porting something i had in javascript to flutter. But it gives me an exception on String that it does not have the instance method '<'. I hope someone can help me fix this. Because i have no clue how to correct this issue.

data.sort((a, b) {
            var aName = a['name'].toLowerCase();
            var bName = b['name'].toLowerCase();
            return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
        });

I get this exception:

E/flutter (16823): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (16823): NoSuchMethodError: Class 'String' has no instance method '<'.

Solution

  • < 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());
    });