How to sort a list that could contain null values with dart null-safety

Viewed 1331

I have a list of strings that may contain null values, how do I sort this list?

I'm using Flutter beta channel so null-safety is checked. This is what I have so far:

List<String?> _list = [
  
 'beta',
 'fotxtrot',
 'alpha',
  null,
  null, 
 'delta',
];

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

How do I get this as the outcome:

_list = [
  null,
  null,
  'alpha',
  'beta',
  'delta',
  'fotxtrot',
];
3 Answers

I encountered this recently and built a one line function based on compareTo documentation:

myList.sort((a, b) => a==null ? 1: b==null? -1 : a.compareTo(b));

NB: This brings the null value at the end of the list. In your case just swap -1 and 1 to have them at the front of your List.

You need to modify your sorting method to handle nullable values, not just ignore them. After handling potential nulls you can compare them normally.

_list.sort((a, b) {
  if(a == null) {
    return -1;
  }
  if(b == null) {
    return 1;
  }
  return a.compareTo(b);
}); 

You could also use whereType:

List<String?> _list = [
  'c',
  'a',
  'd',
  null,
  null,
  'b',
];

void main() {
  var list = _list.whereType<String>().toList();
  list.sort();
  print(list); // [a, b, c, d]
}
Related