Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/65937624/get-nested-json-value-by-index-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}");
    }

    ...
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...