gpt4 book ai didi

json - 如何在 flutter 中使用 API 调用嵌套的 json 数据?

转载 作者:行者123 更新时间:2023-12-05 04:46:52 25 4
gpt4 key购买 nike

我的 JSON 看起来像这样:

{
Info: [
{
c_type_id: "1",
cleaning type: "A Cleaning"
},
{
c_type_id: "2",
cleaning type: "B Cleaning"
},
{
c_type_id: "3",
cleaning type: "C Cleaning"
},
{
c_type_id: "4",
cleaning type: "D Cleaning"
},
{
c_type_id: "5",
cleaning type: "E Cleaning"
},
]
}

代码如下:以下代码由 this 创建第 1 类:

class Album {
List<Info> info;
Album({this.info})
Album.fromJson(Map<String, dynamic> json) {
if (json['Info'] != null) {
info = List<Info>.empty();
json['Info'].forEach((v) {
info.add(new Info.fromJson(v));
});
}
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.info != null) {
data['Info'] = this.info.map((v) => v.toJson()).toList();
}
return data;
}
}

第 2 类:

class Info {
String cTypeId;
String cleaningType;
Info({this.cTypeId, this.cleaningType});
Info.fromJson(Map<String, dynamic> json) {
cTypeId = json['c_type_id'];
cleaningType = json['cleaning type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['c_type_id'] = this.cTypeId;
data['cleaning type'] = this.cleaningType;
return data;
}
}

这是我在执行代码时遇到的错误:错误: 无法将参数类型“List”分配给参数类型“String”。

enter image description here

希望得到帮助!

最佳答案

你应该试试下面的代码你的问题已经解决了->

声明你的API调用函数

Future<List<dynamic>> getInfoData() async {
String url = 'https://fillmmaka.com/gigocleanapi/cleanintypes.php';
var response = await http.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
return json.decode(response.body)['Info'];
}

声明你的小部件

Center(
child: FutureBuilder<List<dynamic>>(
future: getInfoData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var id = snapshot.data[index]['c_type_id'];
var type = snapshot.data[index]['cleaning type'];

return Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green.shade300,
),
borderRadius: BorderRadius.circular(15.0),
),
child: ListTile(
leading: Text(id),
title: Text(type),
),
);
},
),
);
}
return CircularProgressIndicator();
},
),
),

你的屏幕看起来像这样 -> enter image description here

关于json - 如何在 flutter 中使用 API 调用嵌套的 json 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68707692/

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