skip to Main Content

I’m using Flutter to display a JSON file which contains a list of nested arrays like so:

"menu" : [
  { 
    "id" : "array_1",
    "name": "MENU",
    "menu_type": "GREEN",
    "icon": "fa-bars",
    "submenu": [
      {
        "id" : "array_2",
        "name": "Hello",
        "menu_type": "YELLOW",
        "submenu": [
          {
            "id" : "array_3",
            "name": "Elephant"
          }
        ]
      }
    ]
  }
]

Currently I can access the JSON, and display the data in console using:

Future<void> readMenuJson() async {
    final response = await rootBundle.loadString('assets/menu_api.json');
    final data = await json.decode(response);
    List newData = data["data"]["menu"];
    print('NEW DATA = $newData');

    setState(() {
      newData;
    });
  }

However I can’t render it. What I would like is to be able to render each individual array i.e. array_1 as a separate component.

I have tried ListView but no data is showing however not receiving any errors:

        body: ListView.builder(
          itemCount: newData.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Text(newData[index]),
            );
          },
        )

Any input would be greatly appreciated, thank you.

2

Answers


  1.     setState(() {
          newData;
        });
    

    You are not doing anything inside the setState here. It seems you have local newData and a class variable newData. Simply changing

    List newData = data["data"]["menu"];
    

    to

    newData = data["data"]["menu"];
    

    might solve it, so it stores it in the class variable and not in a local variable

    Login or Signup to reply.
  2. There is a package that can display json trees in a view.

    Check out flutter_json_view on pub.dev

    Btw, your ListView code issue seems to be that you’re not selecting any value that can be interpreted as a String:

            body: ListView.builder(
              itemCount: newData.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
    -->           title: Text(newData[index]['name']),
                );
              },
            )
    

    should at least list the names, but still not give you a "real" json view.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search