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'

huangapple go评论67阅读模式
英文:

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'

问题

我的问题是当程序尝试执行ListView时,它会给我报错。当我将其定义为String时,它也会给出相同的错误,但是相反。这就是为什么到处都有日志的主要原因。以下是代码:

模型:

// 要解析此JSON数据,请执行以下操作
//
//     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,
      };
}

显示部分:

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()}"),
                    ],
                  ),
                );
              },
            ),
    );
  }
}

我尝试搜索答案,但每种情况都与我的不同。这是我第一次编写一些Rest API代码,所以可能是原因。

如果有人能告诉我原因,因为我找不到需要调整代码的答案。

英文:

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 &#39;dart:convert&#39;;
FacturasDeVenta facturasDeVentaFromJson(String str) =&gt;
FacturasDeVenta.fromJson(json.decode(str));
String facturasDeVentaToJson(FacturasDeVenta data) =&gt;
json.encode(data.toJson());
class FacturasDeVenta {
int count;
int totalCount;
List&lt;VtaPedG&gt; vtaPedGs;
FacturasDeVenta({
required this.count,
required this.totalCount,
required this.vtaPedGs,
});
factory FacturasDeVenta.fromJson(Map&lt;String, dynamic&gt; json) =&gt;
FacturasDeVenta(
count: json[&quot;count&quot;],
totalCount: json[&quot;total_count&quot;],
vtaPedGs: List&lt;VtaPedG&gt;.from(
json[&quot;vta_ped_g&quot;].map((x) =&gt; VtaPedG.fromJson(x))),
);
Map&lt;String, dynamic&gt; toJson() =&gt; {
&quot;count&quot;: count,
&quot;total_count&quot;: totalCount,
&quot;vtaPedGs&quot;: List&lt;dynamic&gt;.from(vtaPedGs.map((x) =&gt; x.toJson())),
};
}
class VtaPedG {
int id;
int clt;
int emp;
VtaPedG({
required this.id,
required this.clt,
required this.emp,
});
factory VtaPedG.fromJson(Map&lt;String, dynamic&gt; json) =&gt; VtaPedG(
id: int.parse(json[&quot;id&quot;]),
clt: int.parse(json[&quot;clt&quot;]),
emp: int.parse(json[&quot;emp&quot;]),
);
Map&lt;String, dynamic&gt; toJson() =&gt; {
&quot;id&quot;: id,
&quot;clt&quot;: clt,
&quot;emp&quot;: emp,
};
}

The part that shows it:

import &#39;dart:convert&#39;;
import &#39;dart:developer&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:http/http.dart&#39; as http;
import &quot;package:velneoapp/api/api_model.dart&quot;;
class PartesView extends StatefulWidget {
const PartesView({super.key});
@override
State&lt;PartesView&gt; createState() =&gt; _PartesViewState();
}
class _PartesViewState extends State&lt;PartesView&gt; {
bool _isLoaded = true;
@override
void initState() {
super.initState();
_getData();
}
@override
void dispose() {
super.dispose();
_getData();
}
FacturasDeVenta? dataFromAPI;
_getData() async {
try {
String url =
&quot;https://demoapi.velneo.com/verp-api/vERP_2_dat_dat/v1/vta_ped_g?page%5Bsize%5D=20&amp;fields=id,clt,emp&amp;api_key=api123&quot;;
http.Response res = await http.get(Uri.parse(url));
log(&quot;${res.statusCode}&quot;);
if (res.statusCode == 200) {
print(&quot;jiji&quot;);
dataFromAPI = await FacturasDeVenta.fromJson(json.decode(res.body));
_isLoaded = false;
setState(() {});
} else {
throw (&quot;NONOAAAAAAA&quot;);
}
} catch (e) {
print(&quot;NONO&quot;);
log(e.toString());
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(&quot;Partes&quot;),
),
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(&quot;\$${dataFromAPI!.vtaPedGs[index].id.toString()}&quot;),
Text(&quot;\$${dataFromAPI!.vtaPedGs[index].clt.toString()}&quot;),
],
),
);
},
),
);
}
}

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.

答案1

得分: 1

我能看到在 API 响应中,你得到的数据如下:

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

而在你的模型中,你将 emp 解析为 int。请将其类型更改为 String,然后它应该可以正常工作。

class VtaPedG {
  int id;
  int clt;
  String emp;   // 从 int 更改为 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,
      };
}
英文:

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

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

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;   &lt;--- Changed this from int to String
VtaPedG({
required this.id,
required this.clt,
required this.emp,
});
factory VtaPedG.fromJson(Map&lt;String, dynamic&gt; json) =&gt; VtaPedG(
id: int.parse(json[&quot;id&quot;]),
clt: int.parse(json[&quot;clt&quot;]),
emp: json[&quot;emp&quot;],
);
Map&lt;String, dynamic&gt; toJson() =&gt; {
&quot;id&quot;: id,
&quot;clt&quot;: clt,
&quot;emp&quot;: emp,
};
}

huangapple
  • 本文由 发表于 2023年7月3日 18:17:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定