类型 '_InternalLinkedHashMap<String, dynamic>' 不是类型 'Iterable<dynamic>' 的子类型 FLUTTER

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>' FLUTTER

我是 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)

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();
     });
   });

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

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

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

之前

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"}  ));