Home > Software design >  ERROR:flutter/runtime/dart_vm_initializer.cc(41) Unhandled Exception: type 'String' is not
ERROR:flutter/runtime/dart_vm_initializer.cc(41) Unhandled Exception: type 'String' is not

Time:12-29

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

CodePudding user response:

It looks like the issue is with the type of the vData variable. It appears that the vData variable is being set to the result of jsonDecode, which will return a Map<String, dynamic> containing the JSON data. However, the code is trying to access elements in the vData map using string keys, like vData['New_V'], as if it were a list.

To fix the issue, you can try changing the line of code that sets the vData variable to:

vData = jsonDecode(response.body) as Map<String, dynamic>;

This will explicitly cast the result of jsonDecode to the correct type, a Map<String, dynamic>. Then, you can access the values in the map using the correct syntax, like vData['New_V'].

For example, the following code should work:

setState(() {
  newV = vData['New_V'];
  oldV = vData['Old_V'];
});

I hope this helps! Let me know if you have any questions.

CodePudding user response:

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());
   });
}
  • Related