flutter error: type 'String' is not a subtype of type 'int' of 'index'

186 views Asked by At

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

1

There are 1 answers

0
GiuseppeFn On

From the dart documentation:

Use the as operator to cast an object to a particular type if and only if you are sure that the object is of that type.

This means, that if you want to convert an int into a double, there is no problem in that, as both are subtypes of num. But in your example, given in the comments, we can clearly see thatREFINE_WGS84_LAT is a double inside of a String

What this really means, is that as can only be used if two types are compatible, which is not the case for String and double, to fix the very error you are facing, you need to do the following:

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"],
    refineWgs84Lat=double.parse(json["REFINE_WGS84_LAT"]),
  
  Map<String, dynamic> toJson() => {
    "CMPNM_NM": cmpnmNm,
    "REFINE_WGS84_LAT": refineWgs84Lat,
  };
}

But I higly suggest do use the package freezed for making models as such.