1

我正在尝试使用flutter和woocommece api构建一个电子商务应用程序。但是当我尝试按下addtocart按钮时,这就是我得到的:

products:List (1 item)
userId:null
hashCode:383444147
runtimeType:Type (CartRequestModel)

我得到了产品,但没有得到 userId。

这是我的 config.dart:

class Config {
  static String key = "ck_xxxxxxxxxxxxxxxxxxxxxxxxxx";
  static String secret = "cs_xxxxxxxxxxxxxxxxxxxx7dc9feb";
  static String url = "https://gngbd.xyz/wp-json/wc/v3";
  static String customerURL = "/customers";
  static String tokenUR = "https://gngbd.xyz/wp-json/jwt-auth/v1/token";
  static String categoryURL = "/products/categories";
  static String productsURL = "/products";
  static String todayOffersTagId = "20";
  static String addToCartURL = "/addtocart";
  static String cartURL = "/cart";
  static String userId = "4";
}

这是我的 cart_provider.dart :

import 'package:flutter/material.dart';
import 'package:grocerry/api_service.dart';
import 'package:grocerry/models/cart_request_model.dart';
import 'package:grocerry/models/cart_response_model.dart';

class CartProvider with ChangeNotifier {
  ApiService apiService;

  List<CartItem> _cartItems;

  List<CartItem> get CartItems => _cartItems;
  double get totalRecords => _cartItems.length.toDouble();

  CartProvider() {
    apiService = new ApiService();
    // ignore: deprecated_member_use
    _cartItems = new List<CartItem>();
  }

  void resetStreams() {
    apiService = new ApiService();
    // ignore: deprecated_member_use
    _cartItems = new List<CartItem>();
  }

  void addToCart(CartProducts product, Function onCallBack) async {
    CartRequestModel requestModel = new CartRequestModel();
    // ignore: deprecated_member_use
    requestModel.products = new List<CartProducts>();

    if (_cartItems == null) resetStreams();

    _cartItems.forEach((element) {
      requestModel.products.add(new CartProducts(
          productId: element.productId, quantity: element.qty));
    });

    var isProductExists = requestModel.products.firstWhere(
        (prd) => prd.productId == product.productId,
        orElse: () => null);

    if (isProductExists != null) {
      requestModel.products.remove(isProductExists);
    }

    requestModel.products.add(product);

    await apiService.addToCart(requestModel).then((cartResponseModel) {
      if (cartResponseModel.data != null) {
        _cartItems = [];
        _cartItems.addAll(cartResponseModel.data);
      }
      onCallBack(cartResponseModel);
      notifyListeners();
    });
  }
}

在这里,我尝试构建一个 addtocart 函数并调用 api_service.dart 文件

这是我的 ApiService.dart 代码:

Future<CartResponseModel> addToCart(CartRequestModel model) async {
    model.userId = int.parse(Config.userId);

    CartResponseModel responseModel;

    try {
      var response = await Dio().post(
        Config.url + Config.addToCartURL,
        data: model.toJson(),
        options: new Options(
          headers: {
            HttpHeaders.contentTypeHeader: "application/json",
          },
        ),
      );
      if (response.statusCode == 200) {
        responseModel = CartResponseModel.fromJson(response.data);
      }
    } on DioError catch (e) {
      // print(e.message);

      if (e.response.statusCode == 404) {
        print(e.response.statusCode);
      } else {
        print(e.message);
        print(e.request);
      }
    }
    return responseModel;
  }

  Future<CartResponseModel> getCartItems() async {
    CartResponseModel responseModel;

    try {
      String url = Config.url +
          Config.cartURL +
          "?user_id=${Config.userId}&consumer_key=${Config.key}&consumer_secret=${Config.secret}";

      print(url);

      var response = await Dio().post(
        url,
        options: new Options(
          headers: {
            HttpHeaders.contentTypeHeader: "application/json",
          },
        ),
      );

      if (response.statusCode == 200) {
        responseModel = CartResponseModel.fromJson(response.data);
      }
    } on DioError catch (e) {
      print(e.message);
    }
    return responseModel;
  }

我还有两个模型,一个用于购物车请求,另一个用于购物车响应模型,我也提供此代码

这是我的 CartRequest.dart

class CartRequestModel {
  int userId;
  List<CartProducts> products;

  CartRequestModel({this.userId, this.products});

  CartRequestModel.fromJson(Map<String, dynamic> json) {
    userId = json['user_id'];
    if (json['products'] != null) {
      // ignore: deprecated_member_use
      products = new List<CartProducts>();
      json['products'].forEach((v) {
        products.add(new CartProducts.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['user_id'] = this.userId;
    if (this.products != null) {
      data['products'] = this.products.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CartProducts {
  int productId;
  int quantity;

  CartProducts({this.productId, this.quantity});

  CartProducts.fromJson(Map<String, dynamic> json) {
    productId = json['product_id'];
    quantity = json['quantity'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['product_id'] = this.productId;
    data['quantity'] = this.quantity;
    return data;
  }
}

这是我的 CartResponse 模型,下面是我的代码,如果需要,请检查:

class CartResponseModel {
  bool status;
  List<CartItem> data;

  CartResponseModel({this.status, this.data});

  CartResponseModel.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    if (json['data'] != null) {
      // ignore: deprecated_member_use
      data = new List<CartItem>();
      json['data'].forEach((v) {
        data.add(new CartItem.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CartItem {
  int productId;
  String productName;
  String productRegularPrice;
  String productsalePrice;
  String thumbNail;
  int qty;
  double lineTotal;
  double lineSubTotal;

  CartItem(
      {this.productId,
      this.productName,
      this.productRegularPrice,
      this.productsalePrice,
      this.thumbNail,
      this.qty,
      this.lineTotal,
      this.lineSubTotal});

  CartItem.fromJson(Map<String, dynamic> json) {
    productId = json['product_id'];
    productName = json['product_name'];
    productRegularPrice = json['product_regular_price'];
    productsalePrice = json['product_sale_price'];
    thumbNail = json['thumbnail'];
    qty = json['qty'];
    lineSubTotal = double.parse(json['line_subtotal'].toString());
    lineTotal = double.parse(json['line_total'].toString());
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['product_id'] = this.productId;
    data['product_name'] = this.productName;
    data['product_regular_price'] = this.productRegularPrice;
    data['product_sale_price'] = this.productsalePrice;
    data['thumbnail'] = this.thumbNail;
    data['qty'] = this.qty;
    data['line_subtotal'] = this.lineSubTotal;
    data['line_total'] = this.lineTotal;

    return data;
  }
}
4

1 回答 1

0

你需要登录,然后测试这个

于 2021-02-05T21:38:51.400 回答