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

Flutter中如何解决‘String’不是‘index’的‘int’子类型错误

错误原因&修复方案

1. log(arr)报错:type 'List<dynamic>' is not a subtype of type 'String'

log()函数只接受字符串参数,你直接传入了列表类型的arr,触发类型转换错误。只需把列表转为字符串再打印即可:

// 两种方式任选其一
import 'dart:convert';
log(jsonEncode(arr)); // 转成JSON格式字符串输出
// 或者
log(arr.toString()); // 直接转为字符串输出

2. 组件调用时报错:type 'String' is not a subtype of type 'int' of 'index'

这个错误是因为你把列表(List)当成映射(Map)使用了——列表只能用整数作为索引(比如arr[0]),但你误用了字符串索引(比如arr['name'])。

举个常见的错误场景,比如编写ListView时:

// 错误写法:用字符串索引列表
ListView.builder(
  itemCount: arr.length,
  itemBuilder: (context, index) => Text(arr['name']),
)

修正后:

// 正确写法:先通过整数索引取列表元素,再访问元素属性
ListView.builder(
  itemCount: arr.length,
  itemBuilder: (context, index) {
    final country = arr[index];
    return Text(country['name']);
  },
)

3. 额外验证:确保API数据解析正确

检查你的ApiProvider中getCountries方法,如果_request返回的是Dio的Response对象而非解析后的JSON数据,需要修改为返回response.data:

Future<dynamic> getCountries() async {
  dio.interceptors.add(
    LogInterceptor(requestBody: true, responseBody: true)
  );
  try {
    final Response response = await _request(() => dio.get(
      ApiPath.countries,
      options: Options(responseType: ResponseType.json)
    ));
    return response.data; // 返回解析后的JSON数据,而非整个Response对象
  } on DioError catch (ex) {
    log(ex.toString());
    rethrow;
  }
}

如果_request已经处理为返回response.data,此步骤可跳过。

修正后的完整获取数据代码

import 'dart:convert';
import 'dart:developer' as dev;

Future<void> getCountries() async {
  try {
    final response = await _apiService.getCountries();
    var arr = response['list'];
    dev.log(jsonEncode(arr)); // 正确打印列表内容
    // 后续将arr传递给组件时,记得用整数索引遍历使用
  } catch (e) {
    dev.log(e.toString());
    rethrow;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:25:17