Skip to content

Instantly share code, notes, and snippets.

@jorwan
Last active December 31, 2023 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorwan/65b50f4fa9cc2d8c45f115fa337ae73f to your computer and use it in GitHub Desktop.
Save jorwan/65b50f4fa9cc2d8c45f115fa337ae73f to your computer and use it in GitHub Desktop.
Sort list with nulls
void main() {
print("Current list");
var l = [1,5,2,null,0];
print(l);
print("sort it asc with nulls at the beginning");
sortIt(l, asc:true, nullAtEnding: false);
print(l);
print("sort it asc with nulls at the end");
sortIt(l, asc:true, nullAtEnding: true);
print(l);
print("sort it desc with nulls at the beginning");
sortIt(l, asc:false, nullAtEnding: false);
print(l);
print("sort it desc with nulls at the end");
sortIt(l, asc:false, nullAtEnding: true);
print(l);
}
void sortIt(l, {bool asc = true, bool nullAtEnding = true}){
l.sort((a, b) {
int? result;
if (a == null) {
result = 1;
} else if (b == null) {
result = -1;
}
if (result != null) {
result *= nullAtEnding ? 1 : -1;
} else {
if (asc) {
// Ascending Order
result = a.compareTo(b);
} else {
// Descending Order
result = b.compareTo(a);
}
}
return result!;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment