1

I have a JSON response with the following structure.

[
  {
    "branch": "B1",
    "xyz": "0",
    "ABC": "2",
    "MN": "2"
  },
  {
    "branch": "B2",
    "xyz": "0",
    "ABC": "0",
    "MN": "0"
  },
]

In this, only branch is constant. The keys are dynamic in number(column names of a table). As per my requirement I keep altering the table by adding columns. I want to display these in my list view with a item for each branch.

I have used the following list view builder

 ListView.builder(
  itemCount: snapshot.data?.length ?? 0,
  itemBuilder: (BuildContext context, int index) {
  var branch= snapshot.data[index]["branch"];// This is fine as branch is constant                     
  return Myownclass(branch:branch,);
   }),

How to get those dynamic keys( xyx,ABC,MN) and their values and display using custom widget.

1 Answer 1

2

I created a dartpad here so you can play with the below code.

The code uses an index to enter into each part of the json object, which is then given to MyOwnClass, a stateful widget that extracts the keys from the json object (in makeWidgetChildren) and returns a lists of widgets using the extracted keys. and builds the listView using the keys.

I also allowed for varying number of keys in each object to make it as generic as possible.

finally, I updated my answer to mimic getting the data from another source, such as an API call. getJsonResponse() called in MyApp is meant to simulate this call, and how it would be passed to MakeList()

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(body: MakeList(json: getJsonResponse())),
    );
  }
  getJsonResponse(){  return [  
    {"branch": "B1", "xyz": "0", "ABC": "2", "MN": "2", "XYZ": "2"},
    {"branch": "B2", "xyz": "0", "ABC": "0", "MN": "0", "another": "sugar"},
    {"branch": "B3", "xyz": "1", "ABC": "1"},
    {"branch": "B4", "xyz": "0", "ABC": "5", "MN": "69"},
  ];}
}

class MakeList extends StatelessWidget {
final List<Map<String,String>> json;
  MakeList({this.json});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: json.length,
      itemBuilder: (BuildContext context, int index) {
        return MyOwnClass(jsonObject: json[index]);
      },
    );
  }
}

class MyOwnClass extends StatefulWidget {
  final Map<String, String> jsonObject;

  MyOwnClass({this.jsonObject});

  @override
  _MyOwnClassState createState() => _MyOwnClassState();
}

class _MyOwnClassState extends State<MyOwnClass> {
  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Container(
        child: Row(children: makeWidgetChildren(widget.jsonObject)),
      ),
    );
  }

  List<Widget> makeWidgetChildren(jsonObject) {
    List<Widget> children = [];
    jsonObject.keys.forEach(
      (key) => {
        children.add(
          Padding(
              child: Text('${jsonObject[key]}'), padding: EdgeInsets.all(8.0)),
        )
      },
    );
    return children;
  }
}
Sign up to request clarification or add additional context in comments.

11 Comments

No. As the keys (ABC, xyz) etc are not known in advance, i can not use the statement like Text('${jsonObject['xyz']}'). Text('${jsonObject['ABC']}').
Sorry, I missed that. I updated my answer and the dartpad to give you dynamic keys
... and also for a varying number of keys.
Thank u very much. Its working. One more help please. I am getting this response from an API call. So I can not initialize the List. How do i add this JSON response to the List?.
I'm glad that worked for you. As for your JSON response, you shouldn't need to add it to the list, you should pass it to the widget itself. I'll update my answer to put it outside of the widget
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.