-1

I am trying to add items to a cart in a shopping app using Flutter and GetX. I first created repositories and controllers and models, everything works pretty fine unless I am not able to pass the clicked object into the add function.

I can access the clicked object's parameters and print them correctly, but not the object itself! For now it says that The argument type 'List<dynamic>' can't be assigned to the parameter type 'ProductModel'. and that's so normal cus product has a list inside of it, is there a way to access the specific product in this case?

Here is what I have tried so far:

my CartController class:

class CartController extends GetxController {
  final CartRepo cartRepo;
  CartController({required this.cartRepo});

  Map<int, CartModel> _cartItems = {};

  void addItem(ProductModel product, int quantity) {
    _cartItems.putIfAbsent(product.id, () {
      print('Adding item to cart');
      return CartModel(
          id: product.id,
          name: product.title,
          img: product.image,
          quantity: quantity,
          price: product.price,
          isExist: true);
    });
  }
}

my ProductController class:

List<dynamic> _productsList = [];
  List<dynamic> get productsList => _productsList;
  late CartController _cart;

  bool _isLoaded = false;
  bool get isLoaded => _isLoaded;

  int _quantity = 0;
  int get quantity => _quantity;
  int _inCartItems = 0;

  int get inCartItems => _inCartItems + _quantity;

  Future<void> getProducts() async {
    Response response = await productsRepo.getProductsList();
    if (response.statusCode == 200) {
      _productsList = [];
      _productsList.addAll(response.body);
      _isLoaded = true;
      update();
    } 
  }

    void addItem(ProductModel product) {
        _cart.addItemToCart(product, _quantity);
      }

and here is my UI:

    Widget _buildBottomContainer() {
    var products = Get.find<ProductsController>().productsList;
    Get.find<ProductsController>().initProduct(Get.find<CartController>());
    return Container(
        padding: EdgeInsets.all(16),
        child: GetBuilder<ProductsController>(
          builder: (prods) {
            return Row(
              children: [
                OutlinedButton(
                    onPressed: () {},
                    child: Icon(Icons.shopping_bag_outlined,
                        color: style.appColor),
                    style: style.outlineButton()),
                SizedBox(width: 16),
                Expanded(
                    child: ElevatedButton(
                  onPressed: () {
                    prods.addItem(ProductModel.fromJson(products[0]));
                  },
                  child: Text('Buy'),
                  style: style.simpleButton(),
                )),
              ],
            );
          },
        ));
  }
Fedy Belaid
  • 157
  • 11

1 Answers1

0

Solved by adding a specific id for each product then passing it as a route parameter.

Fedy Belaid
  • 157
  • 11