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
);
}
}
Run Code Online (Sandbox Code Playgroud)
JSON:
Future loadProducts() async {
final response = await http.get('https://api.stripe.com/v1/products');
return response.body;
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
产品列表类:
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),
],
)
);
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
错误 :
类“_InternalLinkedHashMap”没有带有匹配参数的实例方法“cast”。
编辑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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11253 次 |
| 最近记录: |