我一直在尝试从 api 以 json 格式获取数据并将其放入 listView。我可以很好地获取数据并将其打印在控制台中,但它不会显示在列表中。当前出现错误
<块引用>NoSuchMethodError: Class '_InternalLinkedHashMap
这是当我尝试解码 json 时出现的。现在我正在尝试使用
data = json.decode(response.body.toString()).cast<products>();
并且也尝试了以下但都给出了相同的错误。
//Map<String, dynamic> map = json.decode(response.body);
//data = map["dataKey"];
下面是我的主要代码以及数据的自定义类。
class MyAppState 扩展状态 { 列出数据;
Future callApi(String category) async{
String username = '400107';
String password = 'rR86zH';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
var url = Uri.parse("https://www.floristone.com/api/rest/flowershop/getproducts?category=" + category);
Response response = await http.get(
url,
headers: <String, String>{'authorization': basicAuth});
data = json.decode(response.body.toString()).cast<products>();
//Map<String, dynamic> map = json.decode(response.body);
//data = map["dataKey"];
print(data);
}
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(
appBar: AppBar(
title: Text("Flowers"),
),
body: Column(children: [
Expanded(
child: data == null
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (context, index){
products item = data[index];
return ListTile(
title: Text(item.name),
subtitle: Text(item.description),
);
}),
),
],),
),
);
}
}
下面的类
class products {
double price;
String dimension;
String name;
String large;
String description;
String small;
String code;
products(
{this.price,
this.dimension,
this.name,
this.large,
this.description,
this.small,
this.code});
products.fromJson(Map<String, dynamic> json) {
price = json['price'];
dimension = json['dimension'];
name = json['name'];
large = json['large'];
description = json['description'];
small = json['small'];
code = json['code'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['price'] = this.price;
data['dimension'] = this.dimension;
data['name'] = this.name;
data['large'] = this.large;
data['description'] = this.description;
data['small'] = this.small;
data['code'] = this.code;
return data;
}
}
答案 0 :(得分:0)
改用
.cast
通常最好使用 Map
答案 1 :(得分:0)
首先,您应该按照 style guide 中的建议将类命名为大写字母。
为了转换 JSON 对象,您可以简单地使用正在定义的 fromJson()
方法。
final product = Products.fromJson(jsonDecode(response.body));
在这种情况下,我假设 response.body
是 String
格式。如果它已经是 Map<String, dynamic>
格式,您可以这样做:
final product = Products.fromJson(response.body);