add method

void add(
  1. PurchasableFood foodItem,
  2. BuildContext context
)

Adds a PurchasableFood item to the cart.

If the item is already in the cart or there is already an item in the cart, a SnackBar is displayed with an error message and the item is not added to the cart.

If the item is successfully added to the cart, a SnackBar is displayed with a success message.

The BuildContext is used to display the SnackBar.

Implementation

void add(PurchasableFood foodItem, BuildContext context) {
  if (_items.contains(foodItem) || _items.length == 1) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          "You can only order one item at a time",
          style: TextStyle(
            color: Theme.of(context).colorScheme.onErrorContainer,
          ),
        ),
        backgroundColor: Theme.of(context).colorScheme.errorContainer,
        behavior: SnackBarBehavior.floating,
        dismissDirection: DismissDirection.horizontal,
        duration: const Duration(seconds: 5),
        showCloseIcon: true,
        closeIconColor: Theme.of(context).colorScheme.onErrorContainer,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
    return;
  }
  _items.add(foodItem);
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text("${foodItem.name} added to cart"),
      // material 3 style
      behavior: SnackBarBehavior.floating,
      dismissDirection: DismissDirection.horizontal,
      duration: const Duration(seconds: 1),
      showCloseIcon: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
    ),
  );
  notifyListeners();
}