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