gpt4 book ai didi

dart - Flutter:_InternalLinkedHashMap 没有实例 > 方法 'cast'

转载 作者:IT王子 更新时间:2023-10-29 07:05:38 24 4
gpt4 key购买 nike

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 具有以下结构(数据包含产品列表):

enter image description here

小部件:

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),
],
)
);
}
);
}
}

错误:

Class '_InternalLinkedHashMap' has no instance method 'cast' with matching arguments.

编辑 1:

我试过: enter image description here错误 : enter image description here

最佳答案

这是我解析 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;
}

关于dart - Flutter:_InternalLinkedHashMap 没有实例 > 方法 'cast',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53378341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com