Created
October 11, 2022 11:49
-
-
Save pjbelo/c312a4ed406c2c617285cc8dc8feeccc to your computer and use it in GitHub Desktop.
Dart & Flutter - Sort an Object List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dart & Flutter - Sort an Object List | |
class Product { | |
String name; | |
String category; | |
double price; | |
Product(this.name, this.category, this.price); | |
String asString() { | |
return "$name, $category, $price"; | |
} | |
} | |
const List productsList = [ | |
["potato", "vegetables", 1], | |
["banana", "fruits", 4.5], | |
["apple", "fruits", 3], | |
["pumpkin", "vegetables", 3.5], | |
["orange", "fruits", 2.5], | |
]; | |
void main() { | |
List<Product> products = | |
productsList.map((p) => Product(p[0], p[1], p[2])).toList(); | |
print("## sorted by price"); | |
products.sort((a, b) => a.price.compareTo(b.price)); | |
products.forEach((p) => print(p.asString())); | |
print("\n## sorted by price DESC"); | |
products.sort((b, a) => a.price.compareTo(b.price)); | |
products.forEach((p) => print(p.asString())); | |
print("\n## sorted by name"); | |
products.sort((a, b) => a.name.compareTo(b.name)); | |
products.forEach((p) => print(p.asString())); | |
print("\n## sorted by category + price"); | |
products.sort((a, b) { | |
int compResult = a.category.compareTo(b.category); | |
if (compResult == 0) { | |
return a.price.compareTo(b.price); | |
} | |
return compResult; | |
}); | |
products.forEach((p) => print(p.asString())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment