Search code examples
flutterdartdayofweekweekday

How to Sort List of Week Day names in flutter in ascending order


I have a list of Week Day names in random order, how to sort it in ascending order e.g. Monday, Tuesday, Wednesday …

List

[Friday, Monday, Sunday, Wednesday]

Desired List

[Monday, Wednesday, Friday, Sunday]

I have tried

list.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));

Solution

  • The issue you're going to have to overcome is that there is no super easy way to get a listing of the days of the week. However, that isn't actually a difficult issue to deal with if you're only needing to deal with this for english - you can just hardcode it.

    Here's an example:

    const weekDays = [
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday"
    ];
    
    final positions = weekDays.asMap().map((ind, day) => MapEntry(day, ind));
    

    The positions is slightly more interesting; by calling asMap, I'm converting the list to a map with the keys being the positions (i.e. 0:"Monday", ... 6:"Friday") and then swapping them. This will result in a slightly faster lookup than just using indexOf, although that's realistically probably an unnecessary optimization in this case.

    Then to sort, you can just use a list's sort method and pass it a custom comparitor function:

    dates.sort((first, second) {
      final firstPos = positions[first] ?? 7;
      final secondPos = positions[second] ?? 7;
      return firstPos.compareTo(secondPos);
    });
    

    Putting it all together, this is what it looks like:

    const weekDays = [
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday"
    ];
    
    final positions = weekDays.asMap().map((ind, day) => MapEntry(day, ind));
    
    void main() {
      final dates = ["Friday", "Monday", "Sunday", "Banana", "Wednesday"];
    
      dates.sort((first, second) {
        final firstPos = positions[first] ?? 8;
        final secondPos = positions[second] ?? 8;
        return firstPos.compareTo(secondPos);
      });
      
      print("sorted: $dates");
    }
    

    Note that if your data isn't complete sanitized, you might want to normalize it to be all lower case, and do the same for your "weekDays" listing.