Dart
Putting it together
Combine the cart class with a menu loop.
Putting it together
All pieces are ready: the Cart class, the addItem, getSubtotal and printCart methods. Now we will combine them in the main flow to create two products in the cart, print the cart and show both the subtotal and the taxed total.
At this stage each method does its own job; main just calls them in order. A well-designed program scales by keeping methods small and focused. If you want to add a new feature to the cart later, you only need to change the relevant method.
Menu loop
The main flow in this project is simple: add two products, print the cart, show the subtotal and the taxed total. In a real app a menu loop could read user input continuously; the loop runs until the user types 'exit'.
In this lesson main will be a one-shot flow. You learned while and do-while loops in the previous section; later you can build a menu loop with them. For now it matters to verify all pieces are called in the right order.
Exercise Write the main function
Write a main function. Create a cart with var cart = Cart();. Add two products with cart.addItem("Notebook", 25.0); and cart.addItem("Pen", 10.0);. Print the cart with cart.printCart();. Print the subtotal with print(cart.getSubtotal()); and the taxed total with print(cart.getSubtotal() * 1.20);. The output must be 4 lines: Notebook 25.0, Pen 10.0, 35.0, 42.0.
Show example 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 printCart() {
for (var i = 0; i < names.length; i++) {
print("${names[i]} ${prices[i]}");
}
}
}
}
void main() {
var cart = Cart();
cart.addItem("Notebook", 25.0);
cart.addItem("Pen", 10.0);
cart.printCart();
print(cart.getSubtotal());
print(cart.getSubtotal() * 1.20);
}
Test yourself
-
Write the taxed total line
cart.printCart();
print(cart.getSubtotal());
print(cart.getSubtotal() ____);
Show answer
cart.printCart();
print(cart.getSubtotal());
print(cart.getSubtotal() * 1.20);
-
Which structure calls all pieces during integration?
// integration flow
- for
- class
- the main function
- if
Show answer
the main function — The main function calls all methods in order.
-
Match each piece to its job
- addItem
- Adds to the cart
- printCart
- Shows the cart
- getSubtotal
- Returns subtotal
- * 1.20
- Returns taxed total
Next lesson: Creating lists