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

替换本地assets/1.json为API接口获取数据报错,求解决方案

API数据获取报错排查与修复

原本从本地assets/1.json读取数据,改为调用API接口后运行报错,代码如下:

static Future<Map<String, DataKuliahModel>> getDataKuliah() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    await Future.delayed(const Duration(seconds: 4));
    // String responseJson = await rootBundle.loadString('assets/1.json');

    Map<String, DataKuliahModel> finalResult = {};
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/perwalian/get_paket',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
    final result = jsonDecode(response)['data'] as Map<String, dynamic>;
    result.forEach((key, value) {
      DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);
      finalResult.addAll({
        key: dataKuliah,
      });
    });
    return finalResult;
  }

报错信息

type 'Response' is not a subtype of type 'String' in type cast

问题原因

http.get返回的是Response类型对象,直接把它传给jsonDecode会出现类型不匹配——jsonDecode需要的是字符串格式的响应体,应该使用response.body来获取接口返回的文本内容。

修正后的代码

static Future<Map<String, DataKuliahModel>> getDataKuliah() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    // 正式环境建议移除不必要的延迟
    // await Future.delayed(const Duration(seconds: 4));

    Map<String, DataKuliahModel> finalResult = {};
    final response = await http.get(
      Uri.parse('$url/auth/mhs_siakad/perwalian/get_paket'),
      headers: {'Authorization': 'Bearer $token'},
    );

    // 先判断响应状态码,处理请求失败场景
    if (response.statusCode != 200) {
      throw Exception('请求失败,状态码:${response.statusCode}');
    }

    final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;
    result.forEach((key, value) {
      finalResult[key] = DataKuliahModel.fromMap(value);
    });
    return finalResult;
  }

额外优化建议

  • 增加响应状态码判断,避免请求失败后继续解析引发更多错误
  • 移除无意义的Future.delayed,正式环境中该延迟会拖慢接口请求效率
  • 可以添加try-catch块捕获JSON解析异常,进一步提升代码健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:20:28