ZZZZZZZZZZZZZZZZZZZZ
ZZZZZZZZZZZZZZZZZZZZ

Reputation: 45

How do i sort a field if I am receiving null at some places in dart?

enter image description here

I am making a firebase query for which this is the output. How do i sort it to (1,2,null,null) order? I have tried list.sort((a,b)=> a[fieldName].compareTo(b[fieldName])

Upvotes: 0

Views: 675

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17141

Assuming you're looking for a solution in dart, you need to provide a sorting function that handles null values, which is something your current solution does not even attempt to do.

The following shows a sorting function that checks if either of the terms are null and handles it accordingly. Otherwise, it uses the default compareTo.

list.sort((a,b) {
     if(a == null && b == null) {
       return 0;
     }
     if(a == null) {
       return 1;
     }
     if(b == null) {
       return -1;
     }
     else {
       return a.compareTo(b);
     }
   });

Upvotes: 1

Related Questions