Search code examples
flutterlistdartobservableflutter-getx

How to make the list observable in Flutter using the getx package?


I want to make a shopping cart, so for that purpose I want to add products to a an observable list where I can to change the quantity of different product from different pages (I can change the quantity from detail screen or cart screen).

Each product must have its own quantity, so I had to use an observable list. How can we declare an observable list?


Solution

  • I am sharing a bettter solution for you to achieve this functionality :

    let us assume your cart data be :

    {
     "product" : {
        "ProductID": "10000",
        "ItemGroup": "",
        "ItemCode": "10000",
        "ProductName": "AIrPro Shoes",
        "BuyPrice": "3000",
        "MRP": "4500",
        "SalePrice": "4500",
        "GST": "0",
        "Remarks": "",
        "HSNCode": "",
        "Points": "0",
        "Brand": "Addidas",
        "PhyStock": "0",
        "PhyStockAmount": "0",
        "GroupName": "TF",
        "CategoryName": "00000",
        "CategoryID": "3",
        "Color": "",
        "Size": "",
        "IsImage": "True",
        "Images": [
          "Products/10000_A.png",
          "Products/10000_B.png"
        ]
      },
      "qty" : 1
    
    }
    

    you can change your fields as per your requirement.

    Step 2 : Now create dart model of above data from here. like this :

    class CartItem {
    
     Product? product;
      int? qty;
    
      CartItem({this.product, this.qty});
    
      CartItem.fromJson(Map<String, dynamic> json) {
        product =
            json['product'] != null ? Product?.fromJson(json['product']) : null;
        qty = json['qty'];
      }
    
      Map<String, dynamic> toJson() {
        final data = <String, dynamic>{};
        if (product != null) {
          data['product'] = product?.toJson();
        }
        data['qty'] = qty;
        return data;
      }
    }
    
    class Product {
      String? productID;
      String? itemGroup;
      String? itemCode;
      String? productName;
      String? buyPrice;
      String? mRP;
      String? salePrice;
      String? gST;
      String? remarks;
      String? hSNCode;
      String? points;
      String? brand;
      String? phyStock;
      String? phyStockAmount;
      String? groupName;
      String? categoryName;
      String? categoryID;
      String? color;
      String? size;
      String? isImage;
      List<dynamic>? images;
    
      Product(
          {this.productID,
          this.itemGroup,
          this.itemCode,
          this.productName,
          this.buyPrice,
          this.mRP,
          this.salePrice,
          this.gST,
          this.remarks,
          this.hSNCode,
          this.points,
          this.brand,
          this.phyStock,
          this.phyStockAmount,
          this.groupName,
          this.categoryName,
          this.categoryID,
          this.color,
          this.size,
          this.isImage,
          this.images});
    
      Product.fromJson(Map<String, dynamic> json) {
        productID = json['ProductID'];
        itemGroup = json['ItemGroup'];
        itemCode = json['ItemCode'];
        productName = json['ProductName'];
        buyPrice = json['BuyPrice'];
        mRP = json['MRP'];
        salePrice = json['SalePrice'];
        gST = json['GST'];
        remarks = json['Remarks'];
        hSNCode = json['HSNCode'];
        points = json['Points'];
        brand = json['Brand'];
        phyStock = json['PhyStock'];
        phyStockAmount = json['PhyStockAmount'];
        groupName = json['GroupName'];
        categoryName = json['CategoryName'];
        categoryID = json['CategoryID'];
        color = json['Color'];
        size = json['Size'];
        isImage = json['IsImage'];
        images = json['Images'];
      }
    
      Map<String, dynamic> toJson() {
        final data = <String, dynamic>{};
        data['ProductID'] = productID;
        data['ItemGroup'] = itemGroup;
        data['ItemCode'] = itemCode;
        data['ProductName'] = productName;
        data['BuyPrice'] = buyPrice;
        data['MRP'] = mRP;
        data['SalePrice'] = salePrice;
        data['GST'] = gST;
        data['Remarks'] = remarks;
        data['HSNCode'] = hSNCode;
        data['Points'] = points;
        data['Brand'] = brand;
        data['PhyStock'] = phyStock;
        data['PhyStockAmount'] = phyStockAmount;
        data['GroupName'] = groupName;
        data['CategoryName'] = categoryName;
        data['CategoryID'] = categoryID;
        data['Color'] = color;
        data['Size'] = size;
        data['IsImage'] = isImage;
        data['Images'] = images;
        return data;
      }
    }
    

    Now create CartController class like this :

    class CartController extends GetxController {
    
    
     var cartData = <CartItem>[].obs;
      @override
      void onInit() {
        super.onInit();
      }
    
      addToCart(GetProductResponse item, context){
       
          if(getIndexByProductId(item.productID.toString())==-1){
            CartItem cartItem = CartItem();
            cartItem.product = Product.fromJson(item.toJson());
            cartItem.qty =1 ;
            cartData.value.add(cartItem);
            cartData.refresh();
          }
      }
    
      
    
      increaseQuantity(String productId, context){
        int index = getIndexByProductId(productId);
        if(index>-1){
            cartData.value[index].qty =cartData.value[index].qty!+1 ;
            cartData.refresh();
    
        }
      }
    
      getCartTotal(){
        double total = 0 ;
        if(cartData.value.length>0){
          cartData.value.forEach((element) {
            double itemtotal = element.qty! * (double.parse(element.product!.salePrice.toString())) ;
            total = total + itemtotal ;
          });
        }
    
        return total ;
    
      }
    
      removeFromCart(String productId){
        int index = getIndexByProductId(productId);
        if(index>-1){
          if(cartData.value[index].qty!>1){
            cartData.value[index].qty =cartData.value[index].qty!-1;
            cartData.refresh();
          }
          else{
            cartData.value.removeAt(index);
            cartData.refresh();
          }
    
        }
      }
    
      getIndexByProductId(String productId){
        int index = -1 ;
        cartData.forEach((element) {
          if(element.product!=null)
          if(element.product!.productID==productId){
            index = cartData.indexOf(element);
          }
        });
        return index ;
      }
    
    }
    

    as you can see we have function for all task : addtocart , remove from cart call these function everytime when you need.

    Note for first time you have to intialize cart controller :

    CartController cartController = Get.put(CartController());
    

    after this you can access cart controller by :

    CartController cartController = Get.find<CartController>();
    

    and lastly you have in cartController :

    var cartData = <CartItem>[].obs;
    

    you can bind this list anywhere you want inside obx widget. Note : you can customize the model or function as per your need like if you want to check stock or any other condition. Save it for later !