You could manually check the compareTo value and decide what to do.
In the below example we use reflection (mirrors) so we can specify a property (reflection isn't necessary, and can be avoided as well).
Here is some code to help you get started:
class Post {
String title;
String author;
Post({this.title = "N/A", this.author = "N/A"});
// partially applicable sorter
static Function(Post, Post) sorter(int sortOrder, String property) {
int handleSortOrder(int sortOrder, int sort) {
if (sortOrder == 1) {
// a is before b
if (sort == -1) {
return -1;
} else if (sort > 0) {
// a is after b
return 1;
} else {
// a is same as b
return 0;
}
} else {
// a is before b
if (sort == -1) {
return 1;
} else if (sort > 0) {
// a is after b
return 0;
} else {
// a is same as b
return 0;
}
}
}
return (Post a, Post b) {
switch (property) {
case "title":
int sort = a.title.compareTo(b.title);
return handleSortOrder(sortOrder, sort);
case "author":
int sort = a.author.compareTo(b.author);
return handleSortOrder(sortOrder, sort);
default:
break;
}
};
}
// sortOrder = 1 ascending | 0 descending
static void sortPosts(List<Post> posts, {int sortOrder = 1, String property = "title"}) {
switch (property) {
case "title":
posts.sort(sorter(sortOrder, property));
break;
case "author":
posts.sort(sorter(sortOrder, property));
break;
default:
print("Unrecognized property $property");
}
}
}
void main() {
List<Post> posts = [
new Post(title: "bart loves ice cream", author: "bart"),
new Post(title: "alex loves ice cream", author: "alex"),
new Post(title: "carl loves ice cream", author: "carl")
];
print("---Sorted by title Ascending(default) order---");
Post.sortPosts(posts);
posts.forEach((p) => print(p.title));
print("---Sorted by title Descending order----");
Post.sortPosts(posts, sortOrder: 0);
posts.forEach((p) => print(p.title));
print("---Sorted by author Ascending order---");
Post.sortPosts(posts, property: "author");
posts.forEach((p) => print(p.author));
}
Output:
---Sorted by title Ascending(default) order---
alex loves ice cream
bart loves ice cream
carl loves ice cream
---Sorted by title Descending order----
carl loves ice cream
bart loves ice cream
alex loves ice cream
---Sorted by author Ascending order---
alex
bart
carl