Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I solve this case of "type 'String' is not a subtype of type 'int'" and type 'int' is not a subtype of type 'String'

My problem is that when the program tries to do the ListView, it gives me that error. And when i define it as String, it gives the same error, but backwards. That’s the main reason why there are logs everywhere. Here is the code:

Model:

// To parse this JSON data, do
//
//     final facturasDeVenta = facturasDeVentaFromJson(jsonString);

import 'dart:convert';

FacturasDeVenta facturasDeVentaFromJson(String str) =>
    FacturasDeVenta.fromJson(json.decode(str));

String facturasDeVentaToJson(FacturasDeVenta data) =>
    json.encode(data.toJson());

class FacturasDeVenta {
  int count;
  int totalCount;
  List<VtaPedG> vtaPedGs;

  FacturasDeVenta({
    required this.count,
    required this.totalCount,
    required this.vtaPedGs,
  });

  factory FacturasDeVenta.fromJson(Map<String, dynamic> json) =>
      FacturasDeVenta(
        count: json["count"],
        totalCount: json["total_count"],
        vtaPedGs: List<VtaPedG>.from(
            json["vta_ped_g"].map((x) => VtaPedG.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "count": count,
        "total_count": totalCount,
        "vtaPedGs": List<dynamic>.from(vtaPedGs.map((x) => x.toJson())),
      };
}

class VtaPedG {
  int id;
  int clt;
  int emp;

  VtaPedG({
    required this.id,
    required this.clt,
    required this.emp,
  });

  factory VtaPedG.fromJson(Map<String, dynamic> json) => VtaPedG(
        id: int.parse(json["id"]),
        clt: int.parse(json["clt"]),
        emp: int.parse(json["emp"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "clt": clt,
        "emp": emp,
      };
}

The part that shows it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import "package:velneoapp/api/api_model.dart";

class PartesView extends StatefulWidget {
  const PartesView({super.key});

  @override
  State<PartesView> createState() => _PartesViewState();
}

class _PartesViewState extends State<PartesView> {
  bool _isLoaded = true;
  @override
  void initState() {
    super.initState();
    _getData();
  }

  @override
  void dispose() {
    super.dispose();
    _getData();
  }

  FacturasDeVenta? dataFromAPI;
  _getData() async {
    try {
      String url =
          "https://demoapi.velneo.com/verp-api/vERP_2_dat_dat/v1/vta_ped_g?page%5Bsize%5D=20&fields=id,clt,emp&api_key=api123";
      http.Response res = await http.get(Uri.parse(url));
      log("${res.statusCode}");
      if (res.statusCode == 200) {
        print("jiji");
        dataFromAPI = await FacturasDeVenta.fromJson(json.decode(res.body));
        _isLoaded = false;
        setState(() {});
      } else {
        throw ("NONOAAAAAAA");
      }
    } catch (e) {
      print("NONO");
      log(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Partes"),
      ),
      body: _isLoaded
          ? const Center(
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              scrollDirection: Axis.vertical,
              itemCount: 10,
              itemBuilder: (context, index) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    children: [
                      Text("\$${dataFromAPI!.vtaPedGs[index].id.toString()}"),
                      Text("\$${dataFromAPI!.vtaPedGs[index].clt.toString()}"),
                    ],
                  ),
                );
              },
            ),
    );
  }
}

I tried searching for an answer, but every case is diferent than mine. It’s my first time coding some Rest API code, so maybe that’s the reason.

If anybody can please tell me why, because I can’t find an answer that I have to adequate the code to.

>Solution :

I can see that in the api response, you are getting data as below

"count": 20,
  "total_count": 20071,
  "vta_ped_g": [
    {
      "id": 1,
      "clt": 4789,
      "emp": "001"
    },
   ]

And in your model, you are parsing the emp as int. Change the type to String and it should work.

class VtaPedG {
  int id;
  int clt;
  String emp;   <--- Changed this from int to String

  VtaPedG({
    required this.id,
    required this.clt,
    required this.emp,
  });

  factory VtaPedG.fromJson(Map<String, dynamic> json) => VtaPedG(
        id: int.parse(json["id"]),
        clt: int.parse(json["clt"]),
        emp: json["emp"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "clt": clt,
        "emp": emp,
      };
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading