I want to serialize data from json data using open api to Dart. However, the error continues, such as type 'String' is not a subtype of type 'int' of 'index'. I need to return the string, but I think I'm trying to return the int type. But I don't know where the problem is.
Below is the code I wrote.
First, it is a file containing json data. I thought there was a string-related error, so I assigned the variable type to Shop.fromJson as double.
class Shop {
final String cmpnmNm;
final double refineWgs84Lat;
Shop({
required this.cmpnmNm,
required this.refineWgs84Lat,
});
Shop.fromJson(Map<String, dynamic> json)
: cmpnmNm=json["CMPNM_NM"] as String,
refineWgs84Lat= json["REFINE_WGS84_LAT"] as double,
Map<String, dynamic> toJson() => {
"CMPNM_NM": cmpnmNm,
"REFINE_WGS84_LAT": refineWgs84Lat,
};
}
The part where the list is generated in the form of List by invoking open api.
Future<List<Shop>> fetchshop() async{
late List<Shop> shopList;
String url = "my url code";
final response = await http.get(Uri.parse(url));
final responseBody = response.body;
final jsonMap = json.decode(responseBody);
shopList = jsonMap.containsKey("GGGOODINFLSTOREST")
? (jsonMap['GGGOODINFLSTOREST']['row'] as List)
.map((e) => Shop.fromJson(e))
.toList()
: List.empty();
if(response.statusCode == 200) {
return shopList;
}else{
throw Exception('Failed to load shop info');
}
}
The part of the main function that outputs api data.
class mapmain extends StatefulWidget {
class _mapmainState extends State<mapmain> {
late Future<List<Shop>> shops;
@override
void initState() {
// TODO: implement initState
super.initState();
shops = fetchshop();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('가게 조회'),),
body: Center(
child: FutureBuilder<List<Shop>>(
future: shops,
builder: (context,snapshot){
if(snapshot.hasData){
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(snapshot.data?.length != 0
? snapshot.data![0].cmpnmNm
: "없음"),
Text(snapshot.data?.length != 0
? snapshot.data![0].refineWgs84Lat.toString()
: "-"),
],
);
}
},
),
),
),
);
}
}
From the dart documentation:
This means, that if you want to convert an
intinto adouble, there is no problem in that, as both are subtypes ofnum. But in your example, given in the comments, we can clearly see thatREFINE_WGS84_LATis adoubleinside of aStringWhat this really means, is that
ascan only be used if two types are compatible, which is not the case forStringand double, to fix the very error you are facing, you need to do the following:But I higly suggest do use the package freezed for making models as such.