Skip to content

Instantly share code, notes, and snippets.

@hotdang-ca
Created September 9, 2021 21:10
Show Gist options
  • Save hotdang-ca/7f36bbb9f334fee3a73f29aa5bdf0230 to your computer and use it in GitHub Desktop.
Save hotdang-ca/7f36bbb9f334fee3a73f29aa5bdf0230 to your computer and use it in GitHub Desktop.
Sample of dart fold method
class PaymentLine {
double price;
String name;
int qty;
PaymentLine({ this.price, this.name, this.qty });
}
void main() {
List<PaymentLine> payments = <PaymentLine>[];
payments.add(PaymentLine()
..name = 'Food'
..price = 10.99
..qty = 1);
payments.add(PaymentLine()
..name = 'Litre of Water'
..price = 2.49
..qty = 5);
payments.add(PaymentLine()
..name = 'Autograph'
..price = 100.0
..qty = 1);
double totalPrice = payments.fold(0, (double previousValue, PaymentLine nextLine) => previousValue += nextLine.price);
int totalQty = payments.fold(0, (int previousValue, PaymentLine nextLine) => previousValue += nextLine.qty);
print('Total Price: $totalPrice (should be 113.48)');
print('Total Qty: $totalQty (should be 7)');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment