Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort List by alphabetical order

Tags:

flutter

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 '<'. 
like image 806
Kevin Walter Avatar asked Apr 05 '18 14:04

Kevin Walter


2 Answers

< 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()); }); 
like image 72
Rémi Rousselet Avatar answered Oct 21 '22 07:10

Rémi Rousselet


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

      List.sort((a, b) => a.toString().compareTo(b.toString())); 
like image 20
Thomas Vallee Avatar answered Oct 21 '22 07:10

Thomas Vallee