[英]get nested json value by index - flutter
I am able to get values from a json file using flutter but since the json data is nested i want to be able to get the first parent and its nested value using an integer number my json data here I am able to get values from a json file using flutter but since the json data is nested i want to be able to get the first parent and its nested value using an integer number my json data here
main.dat主要数据
List<JsonModel> myModel = [];
List<CatSubcategory> subCate = [];
loadData() async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for (var data in jsonDecode) {
data['cat_subcategory'].map((x) {
return subCate.add(
CatSubcategory(subName: x['sub_name'], subImage: x['sub_image']));
}).toList();
myModel.add(JsonModel(
category: data['category'],
catId: data['cat_id'],
catIcon: data['cat_icon'],
catSubcategory: subCate));
setState(() {});
}
int localInt = 0;
for(var index = 0; index < myModel[localInt].catSubcategory.length; index++) {
print(myModel[localInt].catSubcategory[index].subName);
}
} else {
print("Something went wrong!");
}
}
instead of giving me the children of the first one which is "category": "Design & Creativity",
, it will give me all of it from 0 - 3. so please how do i do this而不是给我第一个是"category": "Design & Creativity",
它会给我从0到3的所有内容。所以请问我该怎么做
If you require more explanation please let me know如果您需要更多解释,请告诉我
First Answer第一个答案
I hope this will work for you我希望这对你有用
for(int index = 0; index < myModel[0].catSubcategory.length; index++) {
print("==============>>${myModel[0].catSubcategory[index].subName}");
}
Second Answer第二个答案
First, you need to initialize your localInt
outside of your loadData()
method.首先,您需要在loadData()
方法之外初始化localInt
。 And set it value 0 in your initState()
并在您的initState()
中将其设置为 0
@override
void initState() {
loadData(localInt);
localInt = 0;
super.initState();
}
int localInt;
loadData(int data) async {
....
for(int index = 0; index < myModel[data].catSubcategory.length; index++) {
print("==============>>${myModel[data].catSubcategory[index].subName}");
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.