Home > Software design >  How to use GetX API call json complex
How to use GetX API call json complex

Time:04-07

I am a newbie in the world of flutter and GetX package and I am trying to create a simple app using my API and I have only JSON API and a model how to create my controller and response data??

Here is my JSON response data from the API

{
"isSuccess": true,
  "datacount": 77,
  "data": [
    {
      "provinceID": 1,
      "provinceNameEN": "Bangkok",
      "geoID": 2
    },
    {
      "provinceID": 2,
      "provinceNameEN": "Samut Prakan",
      "geoID": 2
    }
  ],
  "error": {
    "code": null,
    "messageToDeveloper": null,
    "messageToUser": null
  }
}

And this is my model

    // To parse this JSON data, do
//
//     final provicesModel = provicesModelFromJson(jsonString);

import 'dart:convert';

ProvicesModel provicesModelFromJson(String str) => ProvicesModel.fromJson(json.decode(str));

String provicesModelToJson(ProvicesModel data) => json.encode(data.toJson());

class ProvicesModel {
    ProvicesModel({
        this.isSuccess,
        this.datacount,
        this.data,
        this.error,
    });

    bool isSuccess;
    int datacount;
    List<Datum> data;
    Error error;

    factory ProvicesModel.fromJson(Map<String, dynamic> json) => ProvicesModel(
        isSuccess: json["isSuccess"],
        datacount: json["datacount"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
        error: Error.fromJson(json["error"]),
    );

    Map<String, dynamic> toJson() => {
        "isSuccess": isSuccess,
        "datacount": datacount,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
        "error": error.toJson(),
    };
}

class Datum {
    Datum({
        this.provinceId,
        this.provinceNameEn,
        this.geoId,
    });

    int provinceId;
    String provinceNameEn;
    int geoId;

    factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        provinceId: json["provinceID"],
        provinceNameEn: json["provinceNameEN"],
        geoId: json["geoID"],
    );

    Map<String, dynamic> toJson() => {
        "provinceID": provinceId,
        "provinceNameEN": provinceNameEn,
        "geoID": geoId,
    };
}

class Error {
    Error({
        this.code,
        this.messageToDeveloper,
        this.messageToUser,
    });

    dynamic code;
    dynamic messageToDeveloper;
    dynamic messageToUser;

    factory Error.fromJson(Map<String, dynamic> json) => Error(
        code: json["code"],
        messageToDeveloper: json["messageToDeveloper"],
        messageToUser: json["messageToUser"],
    );

    Map<String, dynamic> toJson() => {
        "code": code,
        "messageToDeveloper": messageToDeveloper,
        "messageToUser": messageToUser,
    };
}

This is my services

import 'package:dio/dio.dart';

class ProvinceService {
  var dio = Dio();

  Future<dynamic> provinceService() async {
    return await dio.get(
        'URL');
  }
}

This is my Controller

class RegisterController extends GetxController {
  var provicesList = <ProvicesModel>[].obs;

  void fetchprovices() async {
    ProvinceService request = ProvinceService();

    request.provinceService().then((value) {
      if (value.statusCode == 200) {
        for (var item in value.data) {

<<< Have Error _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable')>>>

provicesList.add(ProvicesModel.fromJson(item));
        }
      } else {
        print('Backend error');
      }
    }).catchError((onError) {
      printError();
    });
  }
}

This is my page response

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

  @override
  State<Register> createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  @override
  void initState() {
    registerController.fetchprovices();
    super.initState();
  }

  final registerController = Get.put(RegisterController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(child: GetX<RegisterController>(
            builder: (controller) {
              return ListView.builder(
                itemCount: controller.provicesList.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('${controller.provicesList[index].datacount}'),
                    subtitle: Text(
                        '${controller.provicesList[index].data[index].provinceNameEn}'),
                  );
                },
              );
            },
          ))
        ],
      ),
    );
  }
}

CodePudding user response:

Refer this for more info :-> getx_dio_example

/////

var provicesList = ProvicesModel().obs;

  void fetchprovices() async {
    ProvinceService request = ProvinceService();
    request.provinceService().then((value) {
      if (value.statusCode == 200) {
        final response = ProvicesModel.fromJson(value.data);
        provicesList.value = response;
      } else {
        print('Backend error');
      }
    }).catchError((onError) {
      printError();
    });
  }

///

return ListView.builder(
      itemCount: controller.provicesList.data.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text('${controller.provicesList.datacount}'),
          subtitle: Text(
              '${controller.provicesList.data[index].provinceNameEn}'),
        );
      },
    );

CodePudding user response:

This is my model

// To parse this JSON data, do
//
//     final provincesModel = provincesModelFromJson(jsonString);

import 'dart:convert';

ProvincesModel provincesModelFromJson(String str) => ProvincesModel.fromJson(json.decode(str));

String provincesModelToJson(ProvincesModel data) => json.encode(data.toJson());

class ProvincesModel {
    ProvincesModel({
        this.isSuccess,
        this.datacount,
        this.data,
        this.error,
    });

    bool? isSuccess;
    int? datacount;
    List<Datum>? data;
    Error? error;

    factory ProvincesModel.fromJson(Map<String, dynamic> json) => ProvincesModel(
        isSuccess: json["isSuccess"],
        datacount: json["datacount"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
        error: Error.fromJson(json["error"]),
    );

    Map<String, dynamic> toJson() => {
        "isSuccess": isSuccess,
        "datacount": datacount,
        "data": List<dynamic>.from(data!.map((x) => x.toJson())),
        "error": error!.toJson(),
    };
}

class Datum {
    Datum({
        this.provinceId,
        this.provinceNameTh,
        this.provinceNameEn,
        this.geoId,
    });

    int? provinceId;
    String? provinceNameTh;
    String? provinceNameEn;
    int? geoId;

    factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        provinceId: json["provinceID"],
        provinceNameTh: json["provinceNameTH"],
        provinceNameEn: json["provinceNameEN"],
        geoId: json["geoID"],
    );

    Map<String, dynamic> toJson() => {
        "provinceID": provinceId,
        "provinceNameTH": provinceNameTh,
        "provinceNameEN": provinceNameEn,
        "geoID": geoId,
    };
}

class Error {
    Error({
        this.code,
        this.messageToDeveloper,
        this.messageToUser,
    });

    dynamic code;
    dynamic messageToDeveloper;
    dynamic messageToUser;

    factory Error.fromJson(Map<String, dynamic> json) => Error(
        code: json["code"],
        messageToDeveloper: json["messageToDeveloper"],
        messageToUser: json["messageToUser"],
    );

    Map<String, dynamic> toJson() => {
        "code": code,
        "messageToDeveloper": messageToDeveloper,
        "messageToUser": messageToUser,
    };
}

this is my controller

class RegisterController extends GetxController {
  var provicesList = ProvincesModel().obs;

  void fetchprovices() async {
    ProvinceService request = ProvinceService();
    request.provinceService().then((value) {
      if (value.statusCode == 200) {
        final response = ProvincesModel.fromJson(value.data);
        provicesList.value = response;
      } else {
        print('Backend error');
      }
    }).catchError((onError) {
      printError();
    });
  }
}

this is my view page

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

  @override
  State<Register> createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  @override
  void initState() {
    registerController.fetchprovices();
    super.initState();
  }

  final registerController = Get.put(RegisterController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(child: GetX<RegisterController>(
            builder: (controller) {
              return ListView.builder(
                itemCount: controller.provicesList.value.datacount,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('${controller.provicesList.value.datacount}'),
                    subtitle: Text(
                        '${controller.provicesList.value.data?[index].provinceNameEn}'),
                  );
                },
              );
            },
          ))
        ],
      ),
    );
  }
}

Thank you DholaHardik for helping me

  • Related