Kevin Walter
Kevin Walter

Reputation: 7176

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 '<'.

Upvotes: 49

Views: 67353

Answers (6)

abhishek dana
abhishek dana

Reputation: 63

void main() {
  List users = [
    {
      "name": "Abhishek",
      "age": 21,
    },
    {
      "name": "Raj",
      "age": 22,
    },
    {
      "name": "Rajesh",
      "age": 23,
    },
    {
      "name": "Aakash",
      "age": 24,
    }
  ];

  users.sort((a, b) => a["name"].compareTo(b["name"]));
  print(users);
}

Output:

[{name: Aakash, age: 24}, {name: Abhishek, age: 21}, {name: Raj, age: 22}, {name: Rajesh, age: 23}]

Upvotes: 4

asasahin
asasahin

Reputation: 109

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

Upvotes: 8

Bansook Nam
Bansook Nam

Reputation: 591

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

Upvotes: 8

griffins
griffins

Reputation: 8254

late answer, i had a similar situation and here is how i solved it

     String a = 'towNnpBiDHRehMh4FhYAYShVFr62';
  String b = 'Yjeq9bA0spdZGmqlbr4J663LyvC3';
  String c = "RdeQo32uUwX3ftBeGm0nFChkzE52";
//if you try to sort the strings without converting them toLowercase ir uppercase you will get different results.
  List<String> _myBranchListName = [
    a.toLowerCase(),
    b.toLowerCase(),
    c.toLowerCase(),
  ];

  _myBranchListName.sort();
//if you want to add to strings from the result
  var userId = "${_myBranchListName[0]}" + "${_myBranchListName[1]}";
  print(userId);

  print(_myBranchListName);

Upvotes: 3

Thomas Vallee
Thomas Vallee

Reputation: 286

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

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

Upvotes: 27

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277467

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

Upvotes: 120

Related Questions