chickenbox
chickenbox

Reputation: 25

Flutter; Sort List of Widgets

I currently have a list of widgets

List<LessonItem> _lessons = [];

One Widget inside this list, added by the user should look like this

LessonItem('Bio', 'Mrs Pithan', 'A1.012', HourMinute('08', '00'),
        HourMinute('11', '50'), Colors.green), //lesson, teacher, room, from, to, color

Now I want to sort the list by a specific property from the widgets. How can I do that?

Thanks for any help!

Upvotes: 1

Views: 2055

Answers (1)

Lucas Garcia
Lucas Garcia

Reputation: 76

I would try with the sort method in dart.

You choose a property you want to sort by, and then define how any two elements will be compared.

Here I'm comparing each element by id (smaller id would en up first after sort):

  _lessons.sort((LessonItem a, LessonItem b) => a.id - b.id);

In this case I'm sorting by name (with the compareTo() method from String):

  _lessons.sort((LessonItem a, LessonItem b) => a.name.compareTo(b.name));

You can find more detailed info and some examples in: dart documentation and this helpful post

Upvotes: 2

Related Questions