fix cart, fix log cart

This commit is contained in:
Phuoc Nguyen
2025-12-11 16:39:25 +07:00
parent e3632d4445
commit fc6a4f038e
4 changed files with 65 additions and 44 deletions

View File

@@ -36,6 +36,7 @@ class CartPage extends ConsumerStatefulWidget {
class _CartPageState extends ConsumerState<CartPage> {
bool _isSyncing = false;
bool _hasLoggedViewCart = false;
// Cart is initialized once in home_page.dart at app startup
// Provider has keepAlive: true, so no need to reload here
@@ -44,29 +45,32 @@ class _CartPageState extends ConsumerState<CartPage> {
// and in checkout button handler for checkout flow.
// No dispose() method needed - using ref.read() in dispose() is unsafe.
void _logViewCartOnce(CartState cartState) {
if (_hasLoggedViewCart || cartState.isEmpty) return;
_hasLoggedViewCart = true;
AnalyticsService.logViewCart(
cartValue: cartState.totalPrice,
items: cartState.items.map((item) => AnalyticsEventItem(
itemId: item.product.productId,
itemName: item.product.name,
price: item.product.basePrice,
quantity: item.quantity.toInt(),
)).toList(),
);
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final cartState = ref.watch(cartProvider);
// Log view cart analytics event only once when page opens
_logViewCartOnce(cartState);
final itemCount = cartState.itemCount;
final hasSelection = cartState.selectedCount > 0;
// Log view cart analytics event when cart has items
if (cartState.isNotEmpty) {
AnalyticsService.logViewCart(
cartValue: cartState.selectedTotal,
items: cartState.items.map((item) => AnalyticsEventItem(
itemId: item.product.productId,
itemName: item.product.name,
price: item.product.basePrice,
quantity: item.quantity.toInt(),
)).toList(),
);
}
return PopScope(
// Intercept back navigation to sync pending updates
onPopInvokedWithResult: (didPop, result) async {
@@ -346,6 +350,7 @@ class _CartPageState extends ConsumerState<CartPage> {
/// Build error banner (shown at top when there's an error but cart has items)
Widget _buildErrorBanner(String errorMessage) {
print(errorMessage);
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),