You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter解析JSON报错:'String'不是'index'的'int'子类型问题解决

问题原因
  • 接口返回的JSON外层是数组(List),jsonDecode解析后得到的vData是List类型,而非Map。你直接用vData['New_V']尝试访问,相当于把字符串作为List的索引,但List的索引必须是整数,因此触发type 'String' is not a subtype of type 'int' of 'index'异常。
  • 另外,接口返回的New_V和Old_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(() {
        // 先取List中的第一个元素(对应接口返回的对象)
        var versionMap = vData[0];
        newV = versionMap['New_V'];
        oldV = versionMap['Old_V'];
      });
      if (newV == KCheckAppVersion) {
        isTheirInternet;
      } else if (oldV == KCheckAppVersion) {
        showDialog();
      } else {
        showDialog();
      }
    }
  } on SocketException catch (_) {}
}
额外优化建议
  • 增加空安全判断:比如先检查vData是否为非空List,再访问vData[0],避免数组为空时的异常。
  • 给vData指定类型:声明为List<dynamic>或List<Map<String, dynamic>>,提升代码可读性和类型安全性。

内容的提问来源于stack exchange,提问作者H Amr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:05:19