Overview
The shopping cart includes:- State management with
CartProviderusing Flutter Provider - Add/remove items with quantity tracking
- Stock validation to prevent over-ordering
- Cart total calculation with automatic price computation
- Checkout flow creating orders in Firestore
- Order history for users and admins
CartProvider
The cart is managed byCartProvider, a ChangeNotifier that maintains cart state:
lib/provider/cart_provider.dart
Cart Operations
Adding Products
- New product: Adds with
cantidadCarrito = 1 - Existing product: Increments
cantidadCarritoby 1 - Stock validation: Throws error if exceeds available stock
- Notifies listeners: Updates UI automatically
Removing Products
- Multiple quantity: Decrements
cantidadCarritoby 1 - Single quantity: Removes product from cart entirely
- Notifies listeners: Updates UI automatically
Clearing Cart
- Removes all items from cart
- Called after checkout to reset cart state
Cart Calculations
Total Amount
Total Items Count
Checkout Flow
Orders are created using thecreateUserOrder function:
lib/service/order.dart
Order Creation Process
- Validate cart is not empty
- Generate order ID using atomic counter
- Normalize cart items to order line items
- Calculate totals for validation
- Create Firestore document in
orderscollection - Return order ID for confirmation display
Order Data Structure
Order Management
Fetching User Orders
lib/service/order.dart
Fetching All Orders (Admin)
lib/service/order.dart
Updating Order Status (Admin)
lib/service/order.dart
Order Status Values
pending- Order placed, awaiting processingprocessing- Order being preparedshipped- Order shipped to customercompleted- Order deliveredcancelled- Order cancelled
Using CartProvider in UI
Setup Provider
Access Cart in Widgets
Add Product to Cart
Display Cart Total
Display Item Count Badge
Best Practices
Stock Validation
Stock Validation
Always validate stock availability before adding to cart. The
addProduct method throws an error if the requested quantity exceeds available stock.Price Formatting
Price Formatting
Prices are stored as strings to preserve formatting (e.g., “49.99”). Parse to double only when calculating totals.
Cart Persistence
Cart Persistence
The current implementation uses in-memory state. For persistent carts across app restarts, consider using shared_preferences or local database storage.
Concurrent Updates
Concurrent Updates
CartProvider uses
notifyListeners() to update UI. All cart modifications are synchronous and thread-safe within the Flutter framework.Related Resources
Product Catalog
Browse products to add to cart
User Roles
Admin order management
Firebase Backend
Order storage in Firestore