【问题标题】:type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>' FLUTTERtype '_InternalLinkedHashMap<String, dynamic>' 不是类型 'Iterable<dynamic>' 的子类型
【发布时间】:2021-06-19 09:06:30
【问题描述】:

我对 Flutter 比较陌生。我想从 API 中获取类别和产品信息。我的类别没有问题,但是在获取产品时,我得到了错误 “未处理的异常:类型 '_InternalLinkedHashMap ' 不是类型 'Iterable' 的子类型”。

我看到了很多这个错误的例子,但我无法将其与自己联系起来。

(产品 API)

static Future<http.Response> getProductsByCategoryId(int categoryId){
    return http.get(Uri.http("10.0.2.2:3000", "products?categoryId=$categoryId"));
  }

(产品类别)

class Product {
  int id;
  int categoryId;
  String productName;
  String quantityPerUnit;
  double unitPrice;
  int unitsInStock;

  Product(this.id, this.categoryId, this.productName, this.quantityPerUnit,
      this.unitPrice, this.unitsInStock);

  Product.fromJson(Map json){
    id = json["id"];
    categoryId = json["categoryId"];
    productName = json["productName"];
    quantityPerUnit = json["quantityPerUnit"];
    unitPrice = double.tryParse(json["unitPrice"].toString()) ;
    unitsInStock = json["unitsInStock"];
  }
Widget buildProductList(BuildContext context) {
    return Expanded(
      child: ListView.builder(itemCount: widget.products.length, itemBuilder: (context, index){
        return Text(widget.products[index].quantityPerUnit);
      }),
    );
void getProductsByCategoryId(Category category) {
   ProductApi.getProductsByCategoryId(category.id).then((response){
     setState(() {
       Iterable list = json.decode(response.body);
       this.products = list.map((product) => Product.fromJson(product)).toList();
     });
   });

【问题讨论】:

  • 能把 ProductApi.getProductsByCategoryId(category.id) 返回的值贴出来吗?

标签: database api flutter android-studio mobile


【解决方案1】:

您可能需要从 json.decode 显式转换返回的地图 Final list = json.decode(response.body).cast&lt;Map&lt;String, dynamic&gt;&gt;(); this.products = list.map((product) =&gt; Product.fromJson(product)).toList();

地图在 dart 中不可迭代:https://medium.com/flutterdevs/collection-in-dart-17493ac9e704

【讨论】:

    【解决方案2】:

    我通过更改以下部分解决了问题

    之前

    return http.get(Uri.http("10.0.2.2:3000", "products?categoryId=$categoryId" ));
    

    之后

     return http.get(Uri.http("10.0.2.2:3000", "products", {"categoryId" : "$categoryId"}  ));
    

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 2019-01-26
      • 2020-11-25
      • 1970-01-01
      • 2019-05-02
      • 2021-01-22
      • 2019-03-14
      • 2018-12-14
      • 2020-03-04
      相关资源
      最近更新 更多