wordpress/lib/utils/ftaf.dart
2025-10-16 11:27:27 +05:30

86 lines
2.4 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wordpress/providers/api_controller.dart';
import 'package:wordpress/viewmodel/cart_screen.dart';
class CartButtonHelper {
static Future<void> addToCartAndNavigate({
required BuildContext context,
required WidgetRef ref,
required product,
required int quantity,
String? selectedColor,
String? selectedWeight,
}) async {
try {
// Show loading indicator
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Row(
children: [
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
),
SizedBox(width: 12),
Text('Adding to cart...'),
],
),
duration: Duration(seconds: 1),
),
);
final cartHelper = ref.read(cartHelperProvider);
int? cartId = ref.read(cartIdProvider);
// Create cart if it doesn't exist
if (cartId == null) {
cartId = await cartHelper.createCart();
ref.read(cartIdProvider.notifier).state = cartId;
}
// Add item to cart with attributes
await cartHelper.addToCart(
productId: product.id ?? 0,
quantity: quantity,
// color: selectedColor,
// size: selectedWeight,
);
if (context.mounted) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Added $quantity x ${product.name} to cart"),
backgroundColor: Colors.green[600],
action: SnackBarAction(
label: "View Cart",
textColor: Colors.white,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CartScreen()),
);
},
),
),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error adding to cart: $e'),
backgroundColor: Colors.red,
),
);
}
}
}
}