【问题标题】:Problem with mapping list of images inside the products list using woocommerce api in flutter在颤振中使用woocommerce api映射产品列表中的图像列表的问题
【发布时间】:2021-09-06 06:46:09
【问题描述】:
class ProductModel {
  late String name;
  late int id;
  late String status;
  late String price;
  late List<Images> images;

  ProductModel(
    this.name,
    this.id,
    this.status,
    this.images,
    this.price,
  );

  ProductModel.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    id = json['id'];
    status = json['status'];
    //images = json['images'];
    images = json['image'];
    if (json['images'] != null) {
      images = new List<Images>(); // error on List<Images>() "The default 'List' constructor //isn't available when null safety is enabled.

      json['images'].forEach((v) {
        images.add(new Images.fromJson(v));
      });
    }
    price = json['price'];
  }

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

// ignore: camel_case_types
class Images {
  late int id;
  late String src;
  late String title;

  Images({
    this.id = 0,
    this.src = "",
    this.title = "",
  });

  Images.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    src = json['src'];
    title = json['title'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['src'] = this.src;
    data['title'] = this.title;
    return data;
  }
}

我想在 Flutter 应用中列出我的 Woocommerce 网站的产品,但是在代码中出现错误,请帮助。请指导我将 JSON 建模为 Dart 类的最佳方法。尝试使用 https://javiercbk.github.io/json_to_dart/ 在线转换,但这会产生很多错误

【问题讨论】:

标签: flutter dart woocommerce


【解决方案1】:

看来你初始化列表不正确。

应该是:

images = <Images>[];

此外,您不再需要使用 new 关键字进行初始化。

【讨论】:

  • 这行得通,谢谢你.. 你能告诉我如何使用 snapshot.data 访问 ListView.builder 中图像列表的唯一第一条记录“src”吗?
  • 在 itemCount 字段中传递 images.length 并在构建器中使用 images[index] 引用它
猜你喜欢
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2021-08-22
  • 2021-09-02
  • 2022-01-01
  • 1970-01-01
  • 2021-08-05
相关资源
最近更新 更多