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

Categories

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

listview - Dynamically display JSON data in data table layout in flutter

I am Creating a Dynamic data table view in flutter , where the column headers and the row values are added dynamically. The data is a Json response,the header is a string array and the data to be displayed in row is also a string array .The goal is to display the data in the table view without any hardcoded values. This is how I have tried is to display the data.

                     return ListView.builder(
                         shrinkWrap: true,
                         scrollDirection: Axis.vertical,
                         itemCount: snapshot.data.dataList.length,
                         itemBuilder: (BuildContext context, int index){
                           return SingleChildScrollView(
                             child: DataTable(
                               columns: (snapshot.data.headerList[index] as List).map((item) =>
                               DataColumn(
                                   label:(
                                       List.generate(item.length,(index){
                                         return Text(item[index].toString());
                                       })
                                   )
                               )).toList(),
                               rows: (snapshot.data.dataList[index].dataList as List).map((item) =>
                               
                               DataRow(
                                 
                                   cells:<DataCell>[
                                     DataCell(
                                         List.generate(item.length,(index){
                                           return Text(item[index].toString());
                                         })
                                     )
                                    ])).toList(),
                             ),

This is the JSON response

 "DayEnd": {
        "ColumnWidths": "40′168′96′96′108′156",
        "Headers": "SL.>′Customer< ′Balance Qty>′Amount>′Oldest / Recent ",
        "FieldSeparator": "′",
        "DataList": [
            {
                "Data": "1. ′ABD ′14 / 14.60′11,090′313 / 313",
                "NextLevelZoomData": [
                    {
                        "Element": "eg7P27fbW/GmCr"
                    },
                    {
                        "Element": "AAA=="
                    }
                ],
                "NextLevelZoomType": 2
            },
            {
                "Data": "2. ′LATA′16′7,921′20 / 9",
                "NextLevelZoomData": [
                    {
                        "Element": "MT63z0m7piukmtJZqdZ"
                    },
                    {
                        "Element": "QT/2zE/AAA="
                    }
                ],
                "NextLevelZoomType": 2
            },
            {
                "Data": "3. ′ANAND′11′915′426 / 426",
                "NextLevelZoomData": [
                    {
                        "Element": "AAA="
                    }
                ],
                "NextLevelZoomType": 2
            },
            {
                "Data": "4. ′Asts′1′1,010′27 / 27",
                "NextLevelZoomData": [
                    {
                        "Element": "w/VbTHwKgQAAA=="
                    }
                ],
                "NextLevelZoomType": 2
            },
            }

The above response gives a string data Headers which is separated by a special character "`",the each character has to be displayed in a each column header so which is converted to an array. Similarly the data as well . The column width that has to be maintained for each data is mentioned in columnWidth Similarly the alignment of the data like if "SL.>" then ">" it has to be right aligned.

I am not sure if this is the right approach to get it, This gives an error

The argument type 'List<Text>' can't be assigned to the parameter type 'Widget'.

Any idea to approach in a better way will be much appreciated.

question from:https://stackoverflow.com/questions/65856234/dynamically-display-json-data-in-data-table-layout-in-flutter

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

1 Reply

0 votes
by (71.8m points)

Step 1:

[
  {
    "DayEnd": [
      {
        "ColumnWidths": "40′168′96′96′108′156",
        "Headers": "SL.>′Customer< ′Balance Qty>′Amount>′Oldest / Recent ",
        "FieldSeparator": "′",
        "DataList": [
          {
            "Data": "1. ′ABD ′14 / 14.60′11,090′313 / 313",
            "NextLevelZoomData": [
              {
                "Element": "eg7P27fbW/GmCr"
              },
              {
                "Element": "AAA=="
              }
            ],
            "NextLevelZoomType": 2
          }
        ]
      }
    ]
  }
]

Step 2:

 class TableModel {
  TableModel(this.headerData, this.rowData);
  List<String> headerData;
  List<List<String>> rowData;

  factory TableModel.fromJson(Map<String, dynamic> json) {
    return TableModel(
      json['DayEnd'][0]["Headers"].split('′').toList(),
      buildRowData(json),
    );
  }
}

List<List<String>> buildRowData(Map<String, dynamic> json){
  List<List<String>> rowDataCollection = [];
  json['DayEnd'][0]["DataList"].forEach((rows){
    rowDataCollection.add(rows['Data'].split('′').toList());
  });

  return rowDataCollection;
}

Step 3:

Future<void> generateList() async {
    String responseBody = await rootBundle.loadString("assets/data.json");
    var list = await json.decode(responseBody).cast<Map<String, dynamic>>();
    return await list
        .map<TableModel>((json) => TableModel.fromJson(json))
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
            appBar: AppBar(
              title: Text('DataTable'),
            ),
            body: FutureBuilder(
              future: generateList(),
              builder: (context, snapShot) {
                if (snapShot.data == null ||
                    snapShot.connectionState == ConnectionState.waiting ||
                    snapShot.hasError ||
                    snapShot.data.length == 0) {
                  return Container(
                    child: Center(child: CircularProgressIndicator()),
                  );
                } else {
                  return ListView.builder(
                      shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                      itemCount: snapShot.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        final TableModel table = snapShot.data[index];
                        return SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: DataTable(
                            columns: table.headerData.map<DataColumn>((e) {
                              var columnName = e;
                              TextAlign align;
                              if (columnName.contains('<')) {
                                align = TextAlign.start;
                                columnName = columnName.replaceAll('<', '');
                              } else if (columnName.contains('>')) {
                                align = TextAlign.end;
                                columnName = columnName.replaceAll('>', '');
                              } else {
                                align = TextAlign.center;
                              }

                              return DataColumn(
                                  label: Text(
                                columnName,
                                textAlign: align,
                              ));
                            }).toList(),
                            rows: table.rowData.map<DataRow>((e) {
                              return DataRow(
                                  cells: e
                                      .map<DataCell>((e) => DataCell(Text(e)))
                                      .toList());
                            }).toList(),
                          ),
                        );
                      });
                }
              },
            )));
  }

DataTable


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...