我对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();
});
});
您可能需要显式转换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"} ));