错误:flutter/runtime/dart_vm_initializer.cc(41)未处理的异常:类型“String”不是json文件flutter的“index”的类型“int”的子类型

8yoxcaq7  于 2022-12-30  发布在  Flutter
关注(0)|答案(1)|浏览(1425)

我正在尝试从JSON文件中获取两个int
这是api响应

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

当我使用jsonDecode获取这两个int时,标记代码中出现错误
我一直收到
未处理的异常:类型"String"不是"index"的类型"int"的子类型
在代码行上
新V = vData ["新V"]. toInt();
这是我的密码

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 (_) {}
 }

我错过了一些东西,但我不知道它是什么,有人能解释原因和修复这行代码吗?
谢啦,谢啦

wtzytmuj

wtzytmuj1#

您的变量是string,并且您不能在string上使用toInt(),请尝试以下方法解析为int

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

此外,您将获得Map列表而不是单个Map,因此vData是Map列表,您需要像这样使用它:

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

相关问题