In Flutter how do I display a list of nested arrays?

35 views Asked by At

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

There are 2 answers

0
Ivo On
    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

0
derZorn On

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.