How to sort a list that could contain null values with dart null-safety
1,002
Solution 1
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.
Solution 2
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);
});
Author by
Brandon Pillay
Updated on December 27, 2022Comments
-
Brandon Pillay over 1 year
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', ];