# Flutter Retail POS App Expert Guidelines ## 🎯 App Overview A Flutter-based Point of Sale (POS) retail application for managing products, categories, and sales transactions with an intuitive tab-based interface. --- ## πŸ€– SUBAGENT DELEGATION SYSTEM πŸ€– **CRITICAL: BE PROACTIVE WITH SUBAGENTS! YOU HAVE SPECIALIZED EXPERTS AVAILABLE!** ### 🚨 DELEGATION MINDSET **Instead of thinking "I'll handle this myself"** **Think: "Which specialist is BEST suited for this task?"** ### πŸ“‹ AVAILABLE SPECIALISTS You have access to these expert subagents - USE THEM PROACTIVELY: #### 🎨 **flutter-widget-expert** - **MUST BE USED for**: Product cards, category grids, cart UI, tab navigation, custom widgets - **Triggers**: "create widget", "build UI", "product card", "category grid", "layout", "animation" #### πŸ“Š **riverpod-expert** - **MUST BE USED for**: Cart state, product selection, category filtering, sales state management - **Triggers**: "state management", "provider", "cart", "async state", "data flow", "sales state" #### πŸ—„οΈ **hive-expert** - **MUST BE USED for**: Product storage, category database, sales history, local cache - **Triggers**: "database", "cache", "hive", "products", "categories", "persistence", "offline" #### 🌐 **api-integration-expert** - **MUST BE USED for**: Product sync, inventory API, payment processing, backend integration - **Triggers**: "API", "HTTP", "sync", "dio", "REST", "backend", "payment" #### πŸ—οΈ **architecture-expert** - **MUST BE USED for**: Feature organization, dependency injection, clean architecture setup - **Triggers**: "architecture", "structure", "organization", "clean code", "refactor" #### ⚑ **performance-expert** - **MUST BE USED for**: Product image caching, grid scrolling, memory optimization - **Triggers**: "performance", "optimization", "memory", "image cache", "slow", "lag", "scroll" ### 🎯 DELEGATION STRATEGY **BEFORE starting ANY task, ASK YOURSELF:** 1. "Which of my specialists could handle this better?" 2. "Should I break this into parts for different specialists?" 3. "Would a specialist complete this faster and better?" ### πŸ’Ό WORK BALANCE RECOMMENDATION: - **Simple Tasks (20%)**: Handle independently - quick fixes, minor updates - **Complex Tasks (80%)**: Delegate to specialists for expert-level results ### πŸ”§ HOW TO DELEGATE ``` # Explicit delegation examples: > Use the flutter-widget-expert to create the product card widget with price and image > Have the riverpod-expert design the shopping cart state management > Ask the hive-expert to create the product and category database schema > Use the api-integration-expert to implement product sync with backend > Have the architecture-expert organize the sales feature structure > Ask the performance-expert to optimize the product grid scrolling ``` --- ## Flutter Best Practices - Use Flutter 3.x features and Material 3 design - Implement clean architecture with Riverpod for state management - Use Hive CE for local database and offline-first functionality - Follow proper dependency injection with GetIt - Implement proper error handling and user feedback - Follow platform-specific design guidelines - Use proper localization for multi-language support ## Retail App Project Structure ``` lib/ core/ constants/ api_constants.dart # API endpoints, timeouts app_constants.dart # App config, defaults ui_constants.dart # Spacing, sizes, durations storage_constants.dart # Hive box names, keys theme/ app_theme.dart # Material 3 theme colors.dart # Color schemes typography.dart # Text styles network/ dio_client.dart # HTTP client setup api_interceptor.dart # Auth, logging interceptors network_info.dart # Connectivity status errors/ exceptions.dart # Custom exceptions failures.dart # Failure classes utils/ formatters.dart # Price, date formatters validators.dart # Input validation extensions.dart # Dart extensions widgets/ custom_button.dart # Reusable buttons loading_indicator.dart # Loading states error_widget.dart # Error displays empty_state.dart # Empty list UI features/ home/ data/ datasources/ cart_local_datasource.dart models/ cart_item_model.dart repositories/ cart_repository_impl.dart domain/ entities/ cart_item.dart repositories/ cart_repository.dart usecases/ add_to_cart.dart remove_from_cart.dart clear_cart.dart calculate_total.dart presentation/ providers/ cart_provider.dart cart_total_provider.dart pages/ home_page.dart widgets/ product_selector.dart cart_item_card.dart cart_summary.dart checkout_button.dart products/ data/ datasources/ product_remote_datasource.dart product_local_datasource.dart models/ product_model.dart repositories/ product_repository_impl.dart domain/ entities/ product.dart repositories/ product_repository.dart usecases/ get_all_products.dart get_products_by_category.dart search_products.dart sync_products.dart presentation/ providers/ products_provider.dart product_search_provider.dart product_filter_provider.dart pages/ products_page.dart widgets/ product_grid.dart product_card.dart product_search_bar.dart product_filter_chip.dart categories/ data/ datasources/ category_remote_datasource.dart category_local_datasource.dart models/ category_model.dart repositories/ category_repository_impl.dart domain/ entities/ category.dart repositories/ category_repository.dart usecases/ get_all_categories.dart get_category_by_id.dart sync_categories.dart presentation/ providers/ categories_provider.dart selected_category_provider.dart pages/ categories_page.dart widgets/ category_grid.dart category_card.dart settings/ data/ datasources/ settings_local_datasource.dart models/ app_settings_model.dart repositories/ settings_repository_impl.dart domain/ entities/ app_settings.dart repositories/ settings_repository.dart usecases/ get_settings.dart update_settings.dart presentation/ providers/ settings_provider.dart theme_provider.dart pages/ settings_page.dart widgets/ settings_section.dart theme_selector.dart language_selector.dart shared/ widgets/ app_bottom_nav.dart # Tab navigation custom_app_bar.dart # Reusable app bar price_display.dart # Currency formatting main.dart app.dart # Root widget with ProviderScope test/ unit/ features/ products/ categories/ home/ widget/ integration/ ``` --- # App Context - Retail POS Application ## About This App A comprehensive Flutter-based Point of Sale (POS) application designed for retail businesses. The app enables merchants to manage their product inventory, organize items by categories, process sales transactions, and maintain business settingsβ€”all through an intuitive tab-based interface optimized for speed and efficiency. ## Target Users - **Retail Store Owners**: Small to medium-sized retail businesses - **Cashiers/Sales Staff**: Front-line employees processing transactions - **Store Managers**: Inventory and business configuration management - **Mobile Vendors**: On-the-go sales at markets, events, or mobile locations ## Core Features ### πŸ“± Tab-Based Navigation (4 Tabs) #### Tab 1: Home/POS Screen **Purpose**: Primary sales interface for selecting products and processing transactions **Key Components**: - **Product Selector**: Quick access to frequently sold products - **Shopping Cart**: Real-time cart display with items, quantities, prices - **Cart Management**: Add, remove, update quantities - **Cart Summary**: Subtotal, tax, discounts, total calculation - **Checkout Flow**: Complete transaction and process payment - **Quick Actions**: Clear cart, apply discounts, process returns **State Management**: - Cart state (items, quantities, totals) - Selected product state - Discount state - Transaction state **Data Requirements**: - Real-time cart updates - Price calculations - Tax computation - Transaction logging #### Tab 2: Products Grid **Purpose**: Browse and search all available products **Key Components**: - **Product Grid**: Responsive grid layout with product cards - **Product Cards**: Image, name, price, stock status, category - **Search Bar**: Real-time product search - **Filter Options**: Category filter, price range, availability - **Sort Options**: Name, price, category, popularity - **Empty States**: No products found UI **State Management**: - Products list state (all products) - Search query state - Filter state (category, price range) - Sort state **Data Requirements**: - Product list from Hive (offline-first) - Product images (cached) - Product search indexing - Category relationships #### Tab 3: Categories Grid **Purpose**: View and manage product categories **Key Components**: - **Category Grid**: Visual grid of all categories - **Category Cards**: Icon/image, name, product count - **Category Selection**: Navigate to products in category - **Empty States**: No categories UI **State Management**: - Categories list state - Selected category state - Products by category state **Data Requirements**: - Category list from Hive - Product count per category - Category images (cached) - Category-product relationships #### Tab 4: Settings **Purpose**: App configuration and business settings **Key Components**: - **Theme Settings**: Light/dark mode toggle - **Language Settings**: Multi-language support - **Currency Settings**: Currency format and symbol - **Tax Configuration**: Tax rates and rules - **Business Info**: Store name, contact, address - **Data Management**: Sync, backup, clear cache - **About**: App version, credits, legal **State Management**: - App settings state - Theme mode state - Language state - Sync state **Data Requirements**: - App settings from Hive - User preferences - Business configuration ## Technical Architecture ### State Management (Riverpod 3.0) #### Core Providers ```dart // Cart Management @riverpod class Cart extends _$Cart { @override List build() => []; void addItem(Product product, int quantity) { /* ... */ } void removeItem(String productId) { /* ... */ } void updateQuantity(String productId, int quantity) { /* ... */ } void clearCart() { /* ... */ } } @riverpod class CartTotal extends _$CartTotal { @override double build() { final items = ref.watch(cartProvider); return items.fold(0.0, (sum, item) => sum + (item.price * item.quantity)); } } // Products Management @riverpod class Products extends _$Products { @override Future> build() async { return await ref.read(productRepositoryProvider).getAllProducts(); } Future syncProducts() async { /* ... */ } } @riverpod class FilteredProducts extends _$FilteredProducts { @override List build() { final products = ref.watch(productsProvider).value ?? []; final searchQuery = ref.watch(searchQueryProvider); final selectedCategory = ref.watch(selectedCategoryProvider); return products.where((p) { final matchesSearch = p.name.toLowerCase().contains(searchQuery.toLowerCase()); final matchesCategory = selectedCategory == null || p.categoryId == selectedCategory; return matchesSearch && matchesCategory; }).toList(); } } // Categories Management @riverpod class Categories extends _$Categories { @override Future> build() async { return await ref.read(categoryRepositoryProvider).getAllCategories(); } Future syncCategories() async { /* ... */ } } // Settings Management @riverpod class AppSettings extends _$AppSettings { @override Future build() async { return await ref.read(settingsRepositoryProvider).getSettings(); } Future updateTheme(ThemeMode mode) async { /* ... */ } Future updateLanguage(String locale) async { /* ... */ } } ``` ### Database Schema (Hive CE) #### Core Hive Boxes ```dart // Box Names const String productsBox = 'products'; const String categoriesBox = 'categories'; const String cartBox = 'cart'; const String settingsBox = 'settings'; const String transactionsBox = 'transactions'; ``` #### Product Model ```dart @HiveType(typeId: 0) class Product extends HiveObject { @HiveField(0) final String id; @HiveField(1) final String name; @HiveField(2) final String description; @HiveField(3) final double price; @HiveField(4) final String? imageUrl; @HiveField(5) final String categoryId; @HiveField(6) final int stockQuantity; @HiveField(7) final bool isAvailable; @HiveField(8) final DateTime createdAt; @HiveField(9) final DateTime updatedAt; } ``` #### Category Model ```dart @HiveType(typeId: 1) class Category extends HiveObject { @HiveField(0) final String id; @HiveField(1) final String name; @HiveField(2) final String? description; @HiveField(3) final String? iconPath; @HiveField(4) final String? color; // Hex color string @HiveField(5) final int productCount; @HiveField(6) final DateTime createdAt; } ``` #### Cart Item Model ```dart @HiveType(typeId: 2) class CartItem extends HiveObject { @HiveField(0) final String productId; @HiveField(1) final String productName; @HiveField(2) final double price; @HiveField(3) final int quantity; @HiveField(4) final String? imageUrl; @HiveField(5) final DateTime addedAt; } ``` #### Transaction Model ```dart @HiveType(typeId: 3) class Transaction extends HiveObject { @HiveField(0) final String id; @HiveField(1) final List items; @HiveField(2) final double subtotal; @HiveField(3) final double tax; @HiveField(4) final double discount; @HiveField(5) final double total; @HiveField(6) final DateTime completedAt; @HiveField(7) final String paymentMethod; } ``` #### App Settings Model ```dart @HiveType(typeId: 4) class AppSettings extends HiveObject { @HiveField(0) final String themeModeString; // 'light', 'dark', 'system' @HiveField(1) final String language; @HiveField(2) final String currency; @HiveField(3) final double taxRate; @HiveField(4) final String storeName; @HiveField(5) final bool enableSync; @HiveField(6) final DateTime lastSyncAt; } ``` ## UI/UX Design Guidelines ### Material 3 Design System - **Primary Color**: Represents brand identity (customizable) - **Secondary Color**: Accents and highlights - **Surface Colors**: Cards, sheets, backgrounds - **Typography**: Material 3 type scale (Display, Headline, Title, Body, Label) ### Product Card Design ```dart // Product card should display: - Product image (with placeholder/error handling) - Product name (2 lines max with ellipsis) - Price (formatted with currency) - Stock status badge (if low stock) - Category badge - Add to cart button/icon - Tap to view details ``` ### Category Card Design ```dart // Category card should display: - Category icon/image - Category name - Product count - Background color (category-specific) - Tap to filter products by category ``` ### Cart Item Design ```dart // Cart item should display: - Product thumbnail - Product name - Unit price - Quantity controls (+/-) - Line total - Remove button ``` ### Responsive Grid Layout - **Mobile Portrait**: 2 columns (products/categories) - **Mobile Landscape**: 3 columns - **Tablet Portrait**: 3-4 columns - **Tablet Landscape**: 4-5 columns - Use `GridView.builder` with `SliverGridDelegate` ## Performance Optimization ### Image Management - Use `cached_network_image` for product images - Implement proper placeholder and error widgets - Optimize image sizes (thumbnails for grids, full size for details) - Cache images in memory and disk - Lazy load images in grid views ### Grid Performance ```dart GridView.builder( itemCount: products.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 0.75, crossAxisSpacing: 12, mainAxisSpacing: 12, ), itemBuilder: (context, index) { return RepaintBoundary( child: ProductCard(product: products[index]), ); }, ); ``` ### Database Optimization - Use lazy boxes for large product datasets - Implement pagination for product lists - Create indexes for frequent queries - Regular database compaction - Efficient query filtering ### State Management Optimization - Use `.select()` for granular rebuilds - Implement proper provider disposal - Cache computed values - Debounce search queries - Optimize cart calculations ## Offline-First Strategy ### Data Flow 1. **Read**: Always read from Hive first (instant UI) 2. **Sync**: Background sync with API when online 3. **Update**: Update Hive and UI when sync completes 4. **Conflict**: Handle conflicts with last-write-wins strategy ### Sync Logic ```dart @riverpod class DataSync extends _$DataSync { @override Future build() async { return await _performSync(); } Future _performSync() async { if (!await ref.read(networkInfoProvider).isConnected) { return SyncStatus.offline; } try { // Sync categories first await ref.read(categoriesProvider.notifier).syncCategories(); // Then sync products await ref.read(productsProvider.notifier).syncProducts(); // Update last sync time await ref.read(settingsProvider.notifier).updateLastSync(); return SyncStatus.success; } catch (e) { return SyncStatus.failed; } } } ``` ## Key Features Implementation ### Search Functionality - Real-time search with debouncing (300ms) - Search by product name, description, category - Display search results count - Clear search button - Search history (optional) ### Cart Operations - Add to cart with quantity - Update quantity with +/- buttons - Remove item with swipe or tap - Clear entire cart with confirmation - Calculate totals in real-time - Persist cart between sessions ### Transaction Processing - Validate cart (not empty, stock available) - Calculate subtotal, tax, discounts - Process payment - Save transaction to Hive - Clear cart after successful transaction - Generate receipt (optional) ### Category Filtering - Filter products by selected category - Show all products when no category selected - Display active filter indicator - Clear filter option ## Error Handling ### Network Errors - Display user-friendly error messages - Show retry button for failed operations - Indicate offline mode - Queue operations for retry when online ### Validation Errors - Validate cart before checkout - Check product availability - Validate quantity inputs - Display inline error messages ### Data Errors - Handle empty states (no products, no categories) - Handle missing images gracefully - Validate data integrity on load - Provide fallback values ## Testing Strategy ### Unit Tests - Cart calculations (total, tax, discounts) - Search filtering logic - Category filtering logic - Price formatting - Data validation ### Widget Tests - Product card rendering - Category card rendering - Cart item rendering - Tab navigation - Search bar functionality ### Integration Tests - Complete checkout flow - Product search and filter - Category selection and filtering - Settings updates - Sync operations ## Development Workflow ### Feature Development Process 1. **Define Requirements**: User stories and acceptance criteria 2. **Design Data Layer**: Models, repositories, data sources 3. **Implement Domain Layer**: Entities, use cases 4. **Create Providers**: Riverpod state management 5. **Build UI**: Widgets, pages, navigation 6. **Test**: Unit, widget, integration tests 7. **Optimize**: Performance profiling and optimization ### Code Review Checklist - [ ] Follows clean architecture principles - [ ] Proper error handling implemented - [ ] Offline-first approach maintained - [ ] Performance optimizations applied - [ ] Proper state management with Riverpod - [ ] Hive models and adapters properly defined - [ ] UI follows Material 3 guidelines - [ ] Accessibility considerations addressed - [ ] Tests written and passing - [ ] Code documentation provided ## Future Enhancements (Roadmap) ### Phase 1 - Current - βœ… Core POS functionality - βœ… Product and category management - βœ… Basic cart and checkout - βœ… Settings management ### Phase 2 - Near Future - πŸ”„ Product variants (size, color) - πŸ”„ Discount codes and promotions - πŸ”„ Multiple payment methods - πŸ”„ Receipt printing - πŸ”„ Sales reports and analytics ### Phase 3 - Future - πŸ“‹ Inventory management - πŸ“‹ Customer management - πŸ“‹ Multi-user support with roles - πŸ“‹ Cloud sync with backend - πŸ“‹ Barcode scanning - πŸ“‹ Integration with payment gateways --- ## Remember: ALWAYS DELEGATE TO SPECIALISTS FOR BETTER RESULTS! When working on this retail POS app: - **UI Tasks** β†’ flutter-widget-expert - **State Management** β†’ riverpod-expert - **Database/Caching** β†’ hive-expert - **API Integration** β†’ api-integration-expert - **Architecture Decisions** β†’ architecture-expert - **Performance Issues** β†’ performance-expert **Think delegation first, implementation second!**