CodeBlanks Logo Icon CodeBlanks

Cart design

Design the class structure for the shopping cart.

Cart design

In this project we will build a shopping cart application step by step. The first step is to design the Cart class that will hold the products. In Dart you use a class to group related data and behavior under one roof; you will see more about classes in a later level.

A cart holds product names and prices. We use a List for this: List<String> names = []; and List<double> prices = [];. You will see more about Lists in the next section; for now know them as an empty list inside square brackets. names.length gives the count and names[i] gives the i-th element.

Fields with List

The Cart class will have two fields: names (product names) and prices (prices). In Dart class fields are defined with a direct declaration: List<String> names = [];. The <String> type parameter says the list holds String elements.

These fields are created separately for each Cart object. So var c1 = Cart(); and var c2 = Cart(); create two carts; c1.names and c2.names are two independent lists. This keeps carts from affecting each other.

Practice Define the Cart class

Define a Cart class. It has List<String> names = []; and List<double> prices = []; fields. The main part already creates a cart and prints cart ready; you only need to define the class. The output on a single line must be cart ready.

Starter code

main.dart
// Define the Cart class here

void main() {
  var cart = Cart();
  print("cart ready");
}

Sample solution

main.dart
class Cart {
  List<String> names = [];
  List<double> prices = [];
}

void main() {
  var cart = Cart();
  print("cart ready");
}

Expected output

cart ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is a class used for in Dart?

main.dart
class Cart { ... }
  • Build a loop
  • Print to the screen
  • Group data and behavior under one roof Correct answer
  • Check a condition

Explanation: A class groups related data and behavior under one roof.

2 Write the List field

Question
class Cart {
  ____
  List<double> prices = [];
}
Answer
class Cart {
  List<String> names = [];
  List<double> prices = [];
}

Explanation: List<String> names = []; declares an empty String list.

3 Match each part to its job

Term Meaning
class Cart Class declaration
List<String> names Name list
List<double> prices Price list
[] Empty list

All lessons in Beginner