Calculating totals
- Dart course
- Beginner
- Lesson 50/116
- 6 min
Learn to compute the subtotal and the tax-inclusive total.
Calculating totals
The subtotal of the cart is the amount before tax and extra fees. The getSubtotal method sums all prices in the prices list and returns a double.
To sum, we initialize a sum variable and walk each price with for-in: double sum = 0; for (var p in prices) { sum += p; } return sum;. The += operator adds the right side to the left variable. After the loop sum holds the total of all prices.
Tax and total
The subtotal is the amount before tax and extra fees. The tax-inclusive total uses subtotal * (1 + taxRate); for a 20% tax you apply a 1.20 multiplier.
In this project getSubtotal returns only the subtotal; the taxed total is computed in main. Separating the two makes it easy to update just the multiplier when the tax rate changes. This separation matters because tax rates vary from country to country.
Practice Write the getSubtotal method
Add a getSubtotal method to the Cart class. Its signature is double getSubtotal(). In the body start with double sum = 0;, walk each price with for (var p in prices), add with sum += p; and return with return sum;. main already adds two products and prints getSubtotal. The output on a single line must be 35.0.
Starter code
class Cart {
List<String> names = [];
List<double> prices = [];
void addItem(String name, double price) {
names.add(name);
prices.add(price);
}
}
// Write the getSubtotal method here
}
void main() {
var cart = Cart();
cart.addItem("Notebook", 25.0);
cart.addItem("Pen", 10.0);
print(cart.getSubtotal());
}Sample solution
class Cart {
List<String> names = [];
List<double> prices = [];
void addItem(String name, double price) {
names.add(name);
prices.add(price);
}
double getSubtotal() {
double sum = 0;
for (var p in prices) {
sum += p;
}
return sum;
}
}
void main() {
var cart = Cart();
cart.addItem("Notebook", 25.0);
cart.addItem("Pen", 10.0);
print(cart.getSubtotal());
}Expected output
35.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each part to its job
| Term | Meaning |
|---|---|
double sum = 0 |
Initialize total |
for (var p in prices) |
Walk each price |
sum += p |
Add the price |
return sum |
Return the total |
2 What does getSubtotal return?
double getSubtotal() { ... }- Subtotal before tax Correct answer
- Tax-inclusive total
- Number of products
- First product price
Explanation: getSubtotal returns the subtotal before tax.
3 Write the return line
double getSubtotal() {
double sum = 0;
for (var p in prices) {
sum += p;
}
____
}
double getSubtotal() {
double sum = 0;
for (var p in prices) {
sum += p;
}
return sum;
}
Explanation: return sum; returns the computed total.