2

As my Problem Says..i want to sort my listView items that are basically songs read by external storage..I want to sort them alphabetically..this is my code for listView

final List<MaterialColor> _colors = Colors.primaries;
@override
Widget build(BuildContext context) {
final rootIW = MPInheritedWidget.of(context);
SongData songData = rootIW.songData;
return new ListView.builder(
  itemCount: songData.songs.length,
  itemBuilder: (context, int index) {
    var s = songData.songs[index];
    final MaterialColor color = _colors[index % _colors.length];
    var artFile =
        s.albumArt == null ? null : new File.fromUri(Uri.parse(s.albumArt));

    return new ListTile(
      dense: false,
      leading: new Hero(
        child: avatar(artFile, s.title, color),
        tag: s.title,
      ),
      title: new Text(s.title),
      subtitle: new Text(
        "By ${s.artist}",
        style: Theme.of(context).textTheme.caption,
      ),
Ankur Singhal
  • 57
  • 2
  • 7

1 Answers1

4

Lists can be sorted very easily in Dart.

To sort alphabetically by song title add this line to the beginning of your build method (or wherever else you want to sort the songs list):

Widget build(BuildContext context) {
  songData.songs.sort((a, b) => a.title.compareTo(b.title));

Note that this sorts the list in place, meaning the sort method does not return a sorted copy of the list, but sorts the existing list directly.

Also check out this other answer.

Oswin Noetzelmann
  • 9,166
  • 1
  • 33
  • 46