flutter - 如何使用 getx 包在 Flutter 中使列表可观察?

标签 flutter list dart observable flutter-getx

我想制作一个购物车,因此为此目的,我想将产品添加到可观察列表中,我可以在其中更改不同页面中不同产品的数量(我可以从详细信息屏幕或购物车屏幕更改数量) )。

每种产品都必须有自己的数量,因此我必须使用可观察的列表。我们如何声明一个可观察列表?

最佳答案

我正在为您分享一个更好的解决方案来实现此功能:

让我们假设您的购物车数据为:

{
 "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

}

您可以根据您的要求更改字段。

第 2 步:现在从 here 创建上述数据的 dart 模型。 像这样:

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;
  }
}

现在创建 CartController 类,如下所示:

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 ;
  }

}

如您所见,我们拥有适用于所有任务的函数:addtocart、从购物车中删除,每次需要时都调用这些函数。

第一次注意,您必须初始化购物车 Controller :

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

之后您可以通过以下方式访问购物车 Controller :

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

最后你在 cartController 中:

var cartData = <CartItem>[].obs;

您可以将此列表绑定(bind)到 obx 小部件内的任何位置。 注意:您可以根据需要自定义型号或功能,例如您想检查库存或任何其他条件。 保存起来供以后使用!

关于flutter - 如何使用 getx 包在 Flutter 中使列表可观察?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73145519/

相关文章:

没有 "direct access"的 Java ArrayList

java - 如何使用 Jackson yaml 以大括号 ([ ]) 格式将 Java 列表打印到 Yaml 列表

c# - 在 C# 中从更接近今天的列表中获取下一个日期

google-maps - 如何在Flutter中设定Google Map的主题?

flutter - 禁用 flutter 中的文本编辑字段

flutter - 如何在 flutter 朔迷离的请求中发送 token ?

flutter - Flutter IOS 平台不允许不安全的 HTTP

events - CLI Dart : onPause, onResume,onDone 未按预期启动

android - 如何在调试时修复 xiaomi/redmi/miui 的 INSTALL_PARSE_FAILED_NO_CERTIFICATES?

java - Flutter FCM后台调用平台特定代码