Flutter 如何在Flatter中将项目添加到自定义列表?
我面临一个小问题,无法将项目添加到自定义列表中Flutter 如何在Flatter中将项目添加到自定义列表?,flutter,Flutter,我面临一个小问题,无法将项目添加到自定义列表中 Future<KitchenProducts> createAlbum(String barcode) async { final http.Response response = await http.post( 'https://mysite', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body:
Future<KitchenProducts> createAlbum(String barcode) async {
final http.Response response = await http.post(
'https://mysite',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'barcode': barcode,
}),
);
// Use the compute function to run parsePhotos in a separate isolate.
print(response.body);
return compute(parseResponse, response.body);
}
KitchenProducts parseResponse(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<KitchenProducts>((json) =>
KitchenProducts.fromJson(json));
}
因此,我得到一个错误:
异常:键入'List您的
createAlbum
函数已返回列表。您的产品
列表期望在每个索引处都有一个厨房产品
,但您正在尝试添加一个厨房产品
列表。我建议打印返回值createAlbum
,或者在调试器中单步执行,以查看返回的内容。您可能需要遍历列表中的映射以提取单个产品,然后将它们添加到列表中。您从哪里得到错误?
List<KitchenProducts> products = [];
await createAlbum(barcodeScanRes).then((value) {
products.add(KitchenProducts(code: value.code, name: value.name, weight: value.weight));
}).catchError((error) {
print(error.toString());
});
class KitchenProducts {
String code;
String name;
double weight;
KitchenProducts({this.code, this.name, this.weight});
factory KitchenProducts.fromJson(Map<String, dynamic> json) {
return KitchenProducts(
code: json['code'],
name: json['name'],
weight: json['weight'],
);
}
}