Skip to content

Instantly share code, notes, and snippets.

@ThinkDigitalSoftware
Created February 2, 2019 19:59
Show Gist options
  • Save ThinkDigitalSoftware/3a297d1134763d0d7d681c2cd42c6d5c to your computer and use it in GitHub Desktop.
Save ThinkDigitalSoftware/3a297d1134763d0d7d681c2cd42c6d5c to your computer and use it in GitHub Desktop.
reduce example with custom items
main(){
List<SalesItem> salesList = List.generate(10, (int i) => SalesItem(i));
print("salesList = $salesList");
// the map function takes one thing and converts it to another. You can use it to take an object,
// perform an operation and return the modified object. The function below unwraps the price so that
// I have a list of ints only. (Since you technically can't "add" [SalesItem]s.
List<int> listOfOnlyPrices =
salesList.map<int>((SalesItem item) => item.price).toList();
// The reduce function goes down the list and adds one item to the next in each list. if you have a List of ints
// i.e. [1, 2, 3] the reduce function, if written like it is below, would return 6. It doesn't have to
// be a sum. You can multiply, subtract, call another function, anything you want. As long as you return
// the type that your list contains. in this case, I must return an int.
print("listOfOnlyPrices = $listOfOnlyPrices");
int totalSales = listOfOnlyPrices.reduce((int price1, int price2) {
return price1 + price2;
});
print("totalSales = $totalSales");
}
// the List.generate() constructor creates a list based on your criteria.
// It's is a faster way to write:
//
// List<SalesItem> salesList = [];
// for (int i = 0; i < 10; i++) {
// salesList.add(SalesItem(i));
// }
class SalesItem {
SalesItem(this.price);
int price;
toString(){
return "price = $price";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment