Adding items
- Dart course
- Beginner
- Lesson 49/116
- 6 min
Learn to add items with the addItem method.
The addItem method
To add a product to the cart we will write the addItem method. This method takes name and price parameters and appends them to the names and prices lists. The method returns no value; its return type is void.
To append an element to a list you use the .add() method: names.add(name);. Keeping the two lists parallel matters: the i-th element of names should have its price as the i-th element of prices. So addItem appends to both.
List.add
The List.add(x) method appends element x to the end of the list. It mutates the original list; it does not return a new list. For example after names.add("Notebook"); the list names has "Notebook" at the end.
Consistency matters with parallel lists: addItem appends to both names and prices. If you append to only one, the lists end up with different lengths and printCart breaks. Practical tip: always append to parallel lists together.
Practice Write the addItem method
Add an addItem method to the Cart class. Its signature is void addItem(String name, double price). In the body append to both lists with names.add(name); and prices.add(price);. main already adds two products and prints item added. The output on a single line must be item added.
Starter code
class Cart {
List<String> names = [];
List<double> prices = [];
}
// Write the addItem method here
}
void main() {
var cart = Cart();
cart.addItem("Notebook", 25.0);
cart.addItem("Pen", 10.0);
print("item added");
}Sample solution
class Cart {
List<String> names = [];
List<double> prices = [];
void addItem(String name, double price) {
names.add(name);
prices.add(price);
}
}
void main() {
var cart = Cart();
cart.addItem("Notebook", 25.0);
cart.addItem("Pen", 10.0);
print("item added");
}Expected output
item added
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the addItem body
void addItem(String name, double price) {
____
}
void addItem(String name, double price) {
names.add(name); prices.add(price);
}
Explanation: Both lists get a parallel append.
2 What does the addItem method do?
cart.addItem("Notebook", 25.0);- Removes a product
- Computes the total
- Prints the cart
- Adds a product to the cart Correct answer
Explanation: addItem adds a new product to the cart.
3 Match each part to its job
| Term | Meaning |
|---|---|
void addItem |
Method declaration |
String name |
Name parameter |
double price |
Price parameter |
names.add(name) |
List append |