【问题标题】:Error: Expected a value of type 'Item', but got one of type '_JsonMap'错误:需要一个“Item”类型的值,但得到一个“_JsonMap”类型的值
【发布时间】:2021-10-23 00:46:00
【问题描述】:

按照教程并一直遵循它,但现在它没有从资产本地加载 JSON 文件并显示此错误 错误:需要一个“Item”类型的值,但得到一个“_JsonMap”类型的值 我试图解决它,但我不能 这是我正在使用的文件

目录

class CatalogModel {
  static List<Item> items = [
    Item(
        id: "Codepur001",
        name: "iPhone 12 Pro",
        desc: "Apple iPhone 12th generation",
        price: 999,
        color: "#33505a",
        image:
            "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRISJ6msIu4AU9_M9ZnJVQVFmfuhfyJjEtbUm3ZK11_8IV9TV25-1uM5wHjiFNwKy99w0mR5Hk&usqp=CAc"),
  ];
}

class Item {
  final String id;
  final String name;
  final String desc;
  final num price;
  final String color;
  final String image;

  Item(
      {required this.id,
      required this.name,
      required this.desc,
      required this.price,
      required this.color,
      required this.image});

  factory Item.fromMap(Map<String, dynamic> map) {
    return Item(
      id: map["id"] as String,
      name: map["name"] as String,
      desc: map["desc"] as String,
      price: map["price"] as int,
      color: map["color"] as String,
      image: map["image"] as String,
    );
  }
  toMap() => {
        "id": id,
        "name": name,
        "desc": desc,
        "price": price,
        "color": color,
        "image": image,
      };
}

获取 JSON 数据的函数。

 loadData() async {
    var catalogJson = await rootBundle.loadString("assets/files/catalog.Json");
    final decodeData = jsonDecode(catalogJson);
    var productData = decodeData["products"];
    CatalogModel.items = List.from(productData);
    CatalogModel.items =
        List.from(productData).map<Item>((item) => Item.fromMap(item)).toList();
    setState(() {});
  }

【问题讨论】:

  • 你应该删除CatalogModel.items = List.from(productData);这一行

标签: json flutter dart


【解决方案1】:

替换这行代码

    CatalogModel.items = List.from(productData);

有了这个

    CatalogModel.items = List<Item>.from(productData.map((model) => Item.fromMap(model)));

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2021-07-13
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2022-01-08
    • 2021-09-13
    • 2021-12-31
    • 2021-12-04
    相关资源
    最近更新 更多