Sthg让我发疯,我尝试在卡中显示json产品,但它不起作用。这是我到目前为止尝试过的:
产品类别:
class Product {
final String id;
Product({this.id});
factory Product.fromJson(Map<String, dynamic> json) {
return new Product(
id: json['id'] as String
);
}
}
JSON:
Future loadProducts() async {
final response = await http.get('https://api.stripe.com/v1/products');
return response.body;
}
json具有以下结构(数据包含产品列表):
小部件:
Widget get _homeView {
return new Column(
children: <Widget>[
new FutureBuilder(
future: loadProducts(),
builder: (context, snapshot) {
List<Product> products = parseJson(snapshot.data.toString());
return !products.isEmpty
? new ProductsList(product: products)
: new CircularProgressIndicator();
}
),
...
]
);
}
List<Product> parseJson(String response) {
final parsed = json.decode(response.toString()).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => new Product.fromJson(json)).toList();
}
ProductsList类:
class ProductsList extends StatelessWidget {
final List<Product> product;
ProductsList({Key key, this.product}) : super(key: key);
@override
Widget build(BuildContext context) {
return new ListView.builder(
itemCount: product == null ? 0 : product.length,
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new Container(
children: <Widget>[
new Text(product[index].id),
],
)
);
}
);
}
}
错误:
类'_InternalLinkedHashMap'没有实例 具有匹配参数的方法“ cast”。
编辑1:
答案 0 :(得分:1)
这是我解析对象的json列表的常用方法(虽然有点简单,但是可以使用):
List<Product> parseJson(String response) {
List<Product> products = new List<Product>();
List jsonParsed = json.decode(response.toString());
for (int i = 0; i < jsonParsed.length; i++) {
products.add(new Product.fromJson(jsonParsed[i]));
}
return products;
}