Search code examples
jsonstringflutterinteger

ERROR:flutter/runtime/dart_vm_initializer.cc(41) Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' for json file ,flutter


I'm trying to get two int from JSON file

This is the api response

[
    {
        "New_V": 30,
        "Old_V": 29
    }
]

When I use jsonDecode to get these two int I get an error in the tagged code

I keep getting

Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

on the code line

newV = vData['New_V'].toInt();

this is my code

isTheirUpdate() async {
   var vData;
   try {
     Response response =
         await get(Uri.parse('https://0000000000000/check_v.json'));
     if (response.statusCode == 200) {
       vData = jsonDecode(response.body);
       print(vData);
       int newV;
       int oldV;
       setState(() {
         newV = vData['New_V'].toInt(); /////////// I get error here "type 'String' is not a subtype of type 'int' of 'index'"
         oldV = vData['Old_V'].toInt();
       });
       if (newV == KCheckAppVersion) {
         isTheirInternet;
       } else if (oldV == KCheckAppVersion) {
         showDialog()
       } else {
         showDialog()
       }
     }
   } on SocketException catch (_) {}
 }

There is something I miss but I don't know what it is Can someone explain the reason and a fix for this line of code?

Thanks


Solution

  • Your variable are string and you can't use toInt() on string, try this way to parse to int:

    newV = int.parse(vData[0]['New_V'].toString());
    oldV = int.parse(vData[0]['Old_V'].toString());
    

    also you are getting list of map not a single map so vData is list of map and you need to use it like this:

    if((vData as List).isNotEmpty){
       setState(() {
          newV = int.parse(vData[0]['New_V'].toString());
          oldV = int.parse(vData[0]['Old_V'].toString());
       });
    }