Search code examples
flutterflutter-getxdio

Fetching list of data from API through Dio in Flutter


I am trying to get the list of data from API through Dio but it is throwing an error as "type 'List' is not a subtype of type 'Map<String, dynamic>'".I am trying to figure out is there anything wrong with the code, can someone help me, I would also like to know how to pass the list to DataRow in view.

Dio Client

import 'package:dio/dio.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

    class Client {
      Dio init({String baseUrl = 'http:some url here'}) {
        Dio dio = Dio();
        dio.interceptors.add(PrettyDioLogger(
          requestHeader: true,
          requestBody: true,
          responseBody: true,
          responseHeader: false,
          error: true,
          compact: true,
          maxWidth: 180,
        ));
        dio.options = BaseOptions(
            followRedirects: false,
            baseUrl: baseUrl,
            validateStatus: (status) {
              if (status != null) {
                return status < 500;
              } else {
                return false;
              }
            },
            contentType: 'application/json',
            headers: {
              // "X-Requested-With": "XMLHttpRequest",
              // HttpHeaders.contentTypeHeader: "application/json",
            });
    
        return dio;
      }
    }

    class ApiResponse<T> {
      ApiResponseStatus status;
      T? data;
      String? message;
      ApiResponse.idle() : status = ApiResponseStatus.idle;
      ApiResponse.loading(this.message) : status = ApiResponseStatus.loading;
      ApiResponse.completed(this.data) : status = ApiResponseStatus.completed;
      ApiResponse.unProcessable(this.message)
          : status = ApiResponseStatus.unProcessable;
      ApiResponse.error(this.message) : status = ApiResponseStatus.error;
      @override
      String toString() {
        return "ApiResponseStatus : $status \n Message : $message \n Data : $data";
      }
    }
    
    enum ApiResponseStatus { idle, loading, completed, unProcessable, error }

Model class

import 'dart:convert';

List<MyAttendanceModel> myAttendanceModelFromJson(String str) =>
    List<MyAttendanceModel>.from(
        json.decode(str).map((x) => MyAttendanceModel.fromJson(x)));

String myAttendanceModelToJson(List<MyAttendanceModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class MyAttendanceModel {
  MyAttendanceModel({
    this.xsl,
    this.ztime,
    this.memberid,
    this.xattendancetime,
    this.xeventName,
    this.xreaderName,
    this.xattendancedate,
  });

  int? xsl;
  DateTime? ztime;
  String? memberid;
  String? xattendancetime;
  String? xeventName;
  String? xreaderName;
  String? xattendancedate;

  factory MyAttendanceModel.fromJson(Map<String, dynamic> json) =>
      MyAttendanceModel(
        xsl: json["xsl"],
        ztime: DateTime.parse(json["ztime"]),
        memberid: json["memberid"],
        xattendancetime: json["xattendancetime"],
        xeventName: json["xeventName"],
        xreaderName: json["xreaderName"],
        xattendancedate: json["xattendancedate"],
      );

  Map<String, dynamic> toJson() => {
        "xsl": xsl,
        "ztime": ztime?.toIso8601String(),
        "memberid": memberid,
        "xattendancetime": xattendancetime,
        "xeventName": xeventName,
        "xreaderName": xreaderName,
        "xattendancedate": xattendancedate,
      };
}

Repository

class MyAttendanceRepo {
  final Dio _dio = Client().init();
  final SecureStorage secureStorage = SecureStorage();
  final MyAttendanceModel myAttendanceModel = MyAttendanceModel();

  Future<ApiResponse<MyAttendanceModel>> myAttendance() async {
    // List<ApiResponse<MyAttendanceModel>> myAttendancelist;
    try {
      var response = await _dio.getUri(
        Uri.parse("MyAttendance?memberid=100514"),
      );
      if (response.statusCode == 200) {
        print(response.data);
        return ApiResponse<MyAttendanceModel>.completed(
          MyAttendanceModel.fromJson(response.data) // (response.data[0]),
        );
      } else {
        return ApiResponse<MyAttendanceModel>.error(
            response.statusCode.toString());
      }
    } on DioError catch (d) {
      return ApiResponse<MyAttendanceModel>.error(d.message);
    } catch (ex) {
      return ApiResponse<MyAttendanceModel>.error(ex.toString());
    }
  }
}

Controller

class MyAttendanceController extends GetxController {
  final MyAttendanceRepo myAttendanceRepo = MyAttendanceRepo();
  var myAttendanceList = <ApiResponse<MyAttendanceModel>>[].obs;
  var title = "My Attendance";

  @override
  void onInit() {
    fetchMyAttendance();
    super.onInit();


  Future fetchMyAttendance() async {
    var response = await myAttendanceRepo.myAttendance();
    if (response.status == ApiResponseStatus.completed) {
      List<MyAttendanceModel> myAttendanceList =
      myAttendanceModelFromJson('response.data').toList();

     
    } else {
      Get.defaultDialog(title: response.message.toString());
    }
  }
}

Part of View

 DataTable(
                border: TableBorder.all(color: Colors.white),
                dataRowColor: MaterialStateColor.resolveWith(
                    (states) => Colors.grey.shade300),
                horizontalMargin: 35.0,
                headingRowColor: MaterialStateColor.resolveWith(
                    (states) => Colors.grey.shade400),
                columnSpacing: 30,
                columns: const [
                  DataColumn(label: Text("date")),
                  DataColumn(label: Text('In Time')),
                  DataColumn(label: Text('Reader Name')),
                ],
                rows: const [
                  DataRow(
                    cells: [
                    // here i would like to show the List of data from API
                      DataCell(Text('02/04/2022')),
                      DataCell(Text('02:26:33 PM')),
                      DataCell(Text('PlageD2Face-1-IN')),
                    ],
                  ),
                ]),

API Response

══════════════════════════════════════════════════════════════╝

I/flutter ( 9391):
I/flutter ( 9391): ╔╣ Response ║ GET ║ Status: 200 OK
I/flutter ( 9391): ║  http://**.**.***.***:***/***/***********/MyAttendance?memberid=100514
I/flutter ( 9391): ╚══════════════════════════════════════════════

══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝
I/flutter ( 9391): ╔ Body
I/flutter ( 9391): ║
I/flutter ( 9391): ║    [
I/flutter ( 9391): ║        {
I/flutter ( 9391): ║             xsl: 31938,
I/flutter ( 9391): ║             ztime: "2021-02-02T11:06:18",
I/flutter ( 9391): ║             zutime: null,
I/flutter ( 9391): ║             zid: 0,
I/flutter ( 9391): ║             xname: null,
I/flutter ( 9391): ║             xlastname: null,
I/flutter ( 9391): ║             xtxnnum: null,
I/flutter ( 9391): ║             xdate: null,
I/flutter ( 9391): ║             memberid: "100514",
I/flutter ( 9391): ║             xRegstatus: null,
I/flutter ( 9391): ║             xref: null,
I/flutter ( 9391): ║             zemail: null,
I/flutter ( 9391): ║             ximgid: 0,
I/flutter ( 9391): ║             xrfidcardno: null,
I/flutter ( 9391): ║             xisactive: false,
I/flutter ( 9391): ║             xsalesperson: null,
I/flutter ( 9391): ║             xnidfileexten: null,
I/flutter ( 9391): ║             xvisafileexten: null,
I/flutter ( 9391): ║             xemail: null,
I/flutter ( 9391): ║             xmobile: null,
I/flutter ( 9391): ║             xphone: null,
I/flutter ( 9391): ║             xfax: null,
I/flutter ( 9391): ║             xprofession: null,
I/flutter ( 9391): ║             oldmemberid: null,
I/flutter ( 9391): ║             xgender: "Female",
I/flutter ( 9391): ║             xdob: null,
I/flutter ( 9391): ║             memberxdob: null,
I/flutter ( 9391): ║             xnationality: null,
I/flutter ( 9391): ║             xcomments: null,
I/flutter ( 9391): ║             xlocation: "Salmiya",
I/flutter ( 9391): ║             xmemberaddresslocation: null,
I/flutter ( 9391): ║             xcarno: null,
I/flutter ( 9391): ║             xcarmodelno: null,
I/flutter ( 9391): ║             xcarcolor: null,
I/flutter ( 9391): ║             xremarks: "AUTO",
I/flutter ( 9391): ║             xattendancetime: "11:06:18 AM",
I/flutter ( 9391): ║             IsMnualAttendance: false,
I/flutter ( 9391): ║             xverifyModeName: "Face",
I/flutter ( 9391): ║             xeventName: "Normal Verify Open",
I/flutter ( 9391): ║             xeventPointName: null,
I/flutter ( 9391): ║             xreaderName: "PlageD2Face-1-IN",
I/flutter ( 9391): ║             xdevname: null,
I/flutter ( 9391): ║             xareaName: null,
I/flutter ( 9391): ║             xdevSn: null,
I/flutter ( 9391): ║             idAPI: null,
I/flutter ( 9391): ║             xattendancedate: "02/02/2021",
I/flutter ( 9391): ║             xcreatedby: "AUTO",
I/flutter ( 9391): ║             xformatdate: null,
I/flutter ( 9391): ║             Isblock: false,
I/flutter ( 9391): ║             strblockunblock: null
I/flutter ( 9391): ║        },
I/flutter ( 9391): ║        {
I/flutter ( 9391): ║             xsl: 31969,
I/flutter ( 9391): ║             ztime: "2020-11-05T18:00:59",
I/flutter ( 9391): ║             zutime: null,
I/flutter ( 9391): ║             zid: 0,
I/flutter ( 9391): ║             xname: null,
I/flutter ( 9391): ║             xlastname: null,
I/flutter ( 9391): ║             xtxnnum: null,
I/flutter ( 9391): ║             xdate: null,
I/flutter ( 9391): ║             memberid: "100514",
I/flutter ( 9391): ║             xRegstatus: null,
I/flutter ( 9391): ║             xref: null,
I/flutter ( 9391): ║             zemail: null,
I/flutter ( 9391): ║             ximgid: 0,
I/flutter ( 9391): ║             xrfidcardno: null,
I/flutter ( 9391): ║             xisactive: false,
I/flutter ( 9391): ║             xsalesperson: null,
I/flutter ( 9391): ║             xnidfileexten: null,
I/flutter ( 9391): ║             xvisafileexten: null,
I/flutter ( 9391): ║             xemail: null,
I/flutter ( 9391): ║             xmobile: null,
I/flutter ( 9391): ║             xphone: null,
I/flutter ( 9391): ║             xfax: null,
I/flutter ( 9391): ║             xprofession: null,
I/flutter ( 9391): ║             oldmemberid: null,
I/flutter ( 9391): ║             xgender: "Female",
I/flutter ( 9391): ║             xdob: null,
I/flutter ( 9391): ║             memberxdob: null,
I/flutter ( 9391): ║             xnationality: null,
I/flutter ( 9391): ║             xcomments: null,
I/flutter ( 9391): ║             xlocation: "Salmiya",
I/flutter ( 9391): ║             xmemberaddresslocation: null,
I/flutter ( 9391): ║             xcarno: null,
I/flutter ( 9391): ║             xcarmodelno: null,
I/flutter ( 9391): ║             xcarcolor: null,
I/flutter ( 9391): ║             xremarks: "AUTO",
I/flutter ( 9391): ║             xattendancetime: "6:00:59 PM",
I/flutter ( 9391): ║             IsMnualAttendance: false,
I/flutter ( 9391): ║             xverifyModeName: "Face",
I/flutter ( 9391): ║             xeventName: "Normal Verify Open",
I/flutter ( 9391): ║             xeventPointName: null,
I/flutter ( 9391): ║             xreaderName: "PlageD2Face-1-IN",
I/flutter ( 9391): ║             xdevname: null,
I/flutter ( 9391): ║             xareaName: null,
I/flutter ( 9391): ║             xdevSn: null,
I/flutter ( 9391): ║             idAPI: null,
I/flutter ( 9391): ║             xattendancedate: "05/11/2020",
I/flutter ( 9391): ║             xcreatedby: "AUTO",
I/flutter ( 9391): ║             xformatdate: null,
I/flutter ( 9391): ║             Isblock: false,
I/flutter ( 9391): ║             strblockunblock: null
I/flutter ( 9391): ║        },

I/flutter ( 9391): ║    [
I/flutter ( 9391): ║
I/flutter ( 9391): ╚════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝
I/flutter ( 9391): ApiResponseStatus.error
[GETX] OPEN DIALOG 918862241

Solution

  • Dio already decodes json data. Convert dynamic list to list of MyAttendanceModel and return list instead of one instance.

          if (response.statusCode == 200) {
            print(response.data);
            return ApiResponse<List<MyAttendanceModel>>.completed(
              response.data.map<MyAttendanceModel>((item) => MyAttendanceModel.fromJson(item)).toList();
            );
          }