How to print api response value print in a DataTable (Row Portion) in flutter?(Want to print Static Key in DataColumn and Value in DataRow is dynamic)

Viewed 22

I want to show data on DataTable on Verticle. I added two Static Data in Column i want add "key" data in "TITLE" and add "value" of this in "VALUE". I am trying to it but its not showing data that i want.

1)Api calling

import 'dart:developer'; import 'dart:io'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'dart:async';

    import 'app_exceptions.dart';
    
    class ApiServiceHandler {l̥
      Future<List<Map<String, dynamic>>> getTableVerticalPerson(
          String urlEndPoint) async {
        log('Api Get url, $urlEndPoint');
        var responseJson;
        try {
          final response = await http.get(Uri.parse(urlEndPoint));
          if (response.statusCode >= 200 && response.statusCode < 300) {
            print("Response Body: ${response.body}");
            responseJson = List<Map<String, dynamic>>.from(
                (_returnResponse(response) as List<dynamic>).map((e) => e));
            print("Response JSON: ${responseJson.toString()}");
          } else {
            log('UnSuccess');
            log("The error message is: ${response.body}");
          }
        } on SocketException {
          log('No Internet');
          throw FetchDataException('No Internet connection');
        }
        log('api get received !');
        return responseJson;
      }
    
    l̥
    }
    
    dynamic _returnResponse(http.Response response) {
      switch (response.statusCode) {
        case 200:
          var responseJson = json.decode(response.body.toString());
          log("HORIZONTAL DATA RESPONSE $responseJson");
          return responseJson;
        case 400:
          throw BadRequestException(response.body.toString());
        case 401:
        case 403:
          throw UnauthorisedException(response.body.toString());
        case 500:
        default:
          throw FetchDataException(
              'ERROR OCCURRED WHILE COMMUNICATION WITH SERVER WITH STATUS CODE : ${response.statusCode}');
      }
    }

2)Structure of Showing Vertcle Data

import 'package:adaptive_scrollbar/adaptive_scrollbar.dart'; import 'package:flutter/material.dart';

class VerticalTableWidgetCommon extends StatelessWidget {
  final List<Map<String, dynamic>> verticalDataList;

  const VerticalTableWidgetCommon({this.verticalDataList, Key key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final verticalScrollController = ScrollController();
    final horizontalScrollController = ScrollController();
    return Scaffold(
      body: SafeArea(
        child: AdaptiveScrollbar(
          underColor: Colors.blueGrey.withOpacity(0.3),
          sliderDefaultColor: Colors.grey.withOpacity(0.7),
          sliderActiveColor: Colors.grey,
          width: 17,
          controller: verticalScrollController,
          child: AdaptiveScrollbar(
            controller: horizontalScrollController,
            position: ScrollbarPosition.bottom,
            underColor: Colors.grey.withOpacity(0.3),
            sliderDefaultColor: Colors.grey.withOpacity(0.7),
            sliderActiveColor: Colors.grey,
            width: 17,
            child: verticalDataList != null
                ? SingleChildScrollView(
                    controller: verticalScrollController,
                    scrollDirection: Axis.vertical,
                    child: SingleChildScrollView(
                      controller: horizontalScrollController,
                      scrollDirection: Axis.horizontal,
                      child: DataTable(
                          border: TableBorder(
                              verticalInside: BorderSide(
                                  width: 0.4, color: Colors.grey.shade600),
                              horizontalInside: BorderSide(
                                  width: 0.4, color: Colors.grey.shade600),
                              left: BorderSide(
                                  width: 0.0, color: Colors.grey.shade100),
                              right: BorderSide(
                                  width: 0.0, color: Colors.grey.shade100),
                              top: BorderSide(
                                  width: 0.1, color: Colors.grey.shade100),
                              bottom: BorderSide(
                                  width: 0.1, color: Colors.grey.shade600)),
                          headingTextStyle: TextStyle(
                              fontWeight: FontWeight.normal,
                              fontSize: 12,
                              color: Colors.grey.shade600),
                          dataTextStyle: TextStyle(
                              fontWeight: FontWeight.normal,
                              fontSize: 12,
                              color: Colors.grey.shade600),
                          headingRowHeight: 25,
                          dataRowHeight: 25,
                          headingRowColor: MaterialStateColor.resolveWith(
                            (states) {
                              return Colors.grey.shade100;
                            },
                          ),
                          dividerThickness: 1.0,
                          columnSpacing: 20.0,
                          horizontalMargin: 5.0,
                          showBottomBorder: false,
                          decoration: BoxDecoration(
                              border: Border.all(
                            width: 0.5,
                            color: Colors.grey.shade600,
                          )),
                          columns: [
                            DataColumn(
                                label: SizedBox(
                              width: MediaQuery.of(context).size.width * 0.20,
                              child: const Center(child: Text('TITLE')),
                            )),
                            DataColumn(
                                label: SizedBox(
                                    width: MediaQuery.of(context).size.width *
                                        0.80,
                                    child: const Center(child: Text('VALUE')))),
                          ],
                          rows: getRows(verticalDataList)),
                    ),
                  )
                : const Center(
                    child: CircularProgressIndicator(
                    color: Colors.blue,
                  )),
          ),
        ),
      ),
    );
  }

  getRows(List<Map<String, dynamic>> data) {
    List<List<dynamic>> lists = [];

    List<DataRow> rowList = [];

    List<List<DataCell>> cells = [];

    for (int i = 0; i < data.length; i++) {
      lists.add(<dynamic>[]);
    }
    int i = 0;
    for (var element in data) {
      element.forEach((key, value) {
        lists[i].add(value);
      });
      i++;
    }

    for (int j = 0; j < lists.length; j++) {
      cells.add(<DataCell>[]);
    }

    for (int i = 0; i < lists.length; i++) {
      for (int j = 0; j < lists[i].length; j++) {
        cells[i].add(DataCell(
          Text(lists[i][j].toString(),
              style: const TextStyle(
                  fontWeight: FontWeight.normal,
                  fontSize: 12,
                  color: Colors.black87)),
        ));
      }
    }
    for (int k = 0; k < cells.length; ++k) {
      rowList.add(
        DataRow(
          cells: cells[k],
          color: k.isEven
              ? MaterialStateColor.resolveWith((states) => Colors.white)
              : MaterialStateColor.resolveWith(
                  (states) => Colors.grey.shade100),
        ),
      );
    }
    return rowList;
  }
}

3)Main dart file

import 'package:flutter/material.dart';
import 'package:api_calling/api_service_handler.dart';
import 'package:commons/vertical_table_widget_common.dart';

class VerticalApiCallingDemo extends StatefulWidget {
  const VerticalApiCallingDemo({Key key}) : super(key: key);

  @override
  State<VerticalApiCallingDemo> createState() => _VerticalApiCallingDemoState();
}

class _VerticalApiCallingDemoState extends State<VerticalApiCallingDemo> {
  List<Map<String, dynamic>> verticalTableList;

  @override
  void initState() {
    super.initState();
    ApiServiceHandler()
        .getTableVerticalPerson(
            "https://run.mocky.io/v3/a0e60aed-b553-4031-915e-ab90d9d6152c")
        .then((value) => verticalTableList = value)
        .then((value) => setState(() {}));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Center(
        child: VerticalTableWidgetCommon(verticalDataList: verticalTableList),
      )),
    );
  }
}
0 Answers
Related