Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

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 '<'.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...