1

flutter と woocommece api を使用して e コマース アプリを構築しようとしていますが、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;
  }

私はまた、2つのモデルを持っています。1つはカートリクエスト用で、もう1つはcarresponseモデル用です。このコードも提供しています

ここに私の 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 に答える