3

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',
];
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
Brandon Pillay
  • 986
  • 1
  • 12
  • 28

3 Answers3

11

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.

Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81
5

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);
}); 
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
0

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]
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440