Menu
Coddy logo textTech

Challenge: Find product

Part of the Fundamentals section of Coddy's Dart journey — lesson 94 of 94.

challenge icon

Challenge

Easy

In this challenge, you'll practice using the find method with lists to locate specific items based on conditions.

You have a list of products in a shopping cart, represented as maps with name, price, and quantity. Your task is to complete the findProduct function that searches for a product by name in the cart.

The function should return the first product that matches the given name, or null if no match is found.

Complete the code to properly implement this search functionality.

Try it yourself

void main() {
  // Shopping cart with products
  List<Map<String, dynamic>> shoppingCart = [
    {'name': 'Laptop', 'price': 999.99, 'quantity': 1},
    {'name': 'Headphones', 'price': 59.99, 'quantity': 2},
    {'name': 'Mouse', 'price': 24.99, 'quantity': 1},
    {'name': 'Keyboard', 'price': 49.99, 'quantity': 1}
  ];
  
  // Test the findProduct function
  Map<String, dynamic>? foundProduct = findProduct(shoppingCart, 'Headphones');
  if (foundProduct != null) {
    print('Found: ${foundProduct['name']} - \$${foundProduct['price']} (Quantity: ${foundProduct['quantity']})');
  } else {
    print('Product not found');
  }
  
  // Test with a product that doesn't exist
  foundProduct = findProduct(shoppingCart, 'Monitor');
  if (foundProduct != null) {
    print('Found: ${foundProduct['name']} - \$${foundProduct['price']} (Quantity: ${foundProduct['quantity']})');
  } else {
    print('Product not found');
  }
}

// TODO: Complete this function to find a product by name
Map<String, dynamic>? findProduct(List<Map<String, dynamic>> cart, String productName) {
  // TODO: Loop through the cart and return the first product that matches the productName
  // TODO: Return null if no matching product is found
  
}

All lessons in Fundamentals