skip to Main Content

I have come across similar posts but not one that addresses my problem.

I have a list of objects that I would like to sort from latest to oldest based on lastViewDate value which can be null/empty

The following crashes my app as it is obviously expecting a value for lastVenueDate field

myList.sort((a, b) => b.lastVenueViewDate!.compareTo(a.lastVenueViewDate!));

I have tried to update my code to this but got stuck.

myList.sort((a, b) => b.lastVenueViewDate == null ? <what to do here> : b.lastVenueViewDate.compareTo(a.lastVenueViewDate));

3

Answers


  1. After checking the value of the date, if it is null
    you can set any default value to it.
    So that it can be compared with the other values of the list.
    This can solve your problem

    Login or Signup to reply.
  2. Common is to sort null values first or last in a list compared to defined values. So either return -1 or 1 where you wrote what to do here. If both a and b are null, you could e.g. return 0.

    Login or Signup to reply.
  3. To add a bit more concrete code, if you want nulls to sort before all entries with DateTime proper, use something like this:

    import 'package:collection/collection.dart'; // add to pubspec
    
    final one = DateTime(1); // year 1
    myList.sortBy((e) => e.lastVenueViewDate ?? one);
    

    To have nulls to sort after, change "1" to "99999".

    This uses the convenient sortBy from package collection, a first-party package of cool stuff.

    (And yes, a full-blown .compareBy can process the nulls specially, but this is easier to understand.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search