Reputation: 768
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
If you require more explanation please let me know
Upvotes: 0
Views: 341
Reputation: 2130
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. And set it value 0 in your initState()
@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}");
}
...
}
Upvotes: 1