addToCart method

Future<Cart> addToCart({
  1. required String cartId,
  2. required String sku,
  3. required int quantity,
  4. Map<String, dynamic>? productOptions,
})

Add item to guest cart.

Adds a product to the specified guest cart with the given quantity and options.

cartId the ID of the cart to add the item to sku the product's SKU to add quantity the quantity to add productOptions optional product options (size, color, etc.)

Returns the updated Cart object. Throws an exception if the item cannot be added.

Implementation

Future<Cart> addToCart({
  required String cartId,
  required String sku,
  required int quantity,
  Map<String, dynamic>? productOptions,
}) async {
  try {
    final data = {
      'cartItem': {'sku': sku, 'qty': quantity, 'quote_id': cartId},
    };

    if (productOptions != null) {
      data['cartItem']!['product_option'] = productOptions;
    }

    final response = await _client.guestRequest<Map<String, dynamic>>(
      '/rest/V1/guest-carts/$cartId/items',
      data: data,
      options: Options(method: 'POST'),
    );

    if (response.statusCode == 200) {
      return Cart.fromJson(response.data!);
    } else {
      throw Exception(
        'Failed to add item to cart: ${response.statusMessage}',
      );
    }
  } on DioException catch (e) {
    throw Exception('Failed to add item to cart: ${e.message}');
  } catch (e) {
    throw Exception('Failed to add item to cart: $e');
  }
}