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

Flutter中如何从Dio响应的嵌套列表中获取对象数据

问题说明

在Flutter项目中使用Dio发起API请求时,无法正确识别响应中的嵌套列表结构,无法获取内层列表的完整对象数据,当前实现的指标列表拉取方法相关代码如下:

void fetchAllIndicatorsList(int ModuleId) async {
try {
  isLoading(true);
  var indicatorslist = await DioClient.fetchAllIndicators(ModuleId);
  if (indicatorslist != null) {
    Indicatorslist.clear();
first list ==>   IndicatorsChecklist.clear();

    Indicatorslist.value = indicatorslist;


    for(var i=0; Indicatorslist.length>0; i++){

      ==> second list IndicatorsChecklist.assignAll(Indicatorslist[i].indicators!.length.obs.toJson());

    }
  }
} finally {
  isLoading(false);
}
}
问题根因

代码存在3个核心逻辑错误:

  • 循环终止条件写错:for(var i=0; Indicatorslist.length>0; i++)的判断逻辑是「只要外层列表长度大于0就一直循环」,会直接触发死循环+数组越界崩溃,根本走不到正常的遍历赋值流程
  • 内层数据取值完全错误:Indicatorslist[i].indicators!.length.obs.toJson()取的是内层列表的长度数值,不是内层列表里存的指标对象本身,自然拿不到完整的对象数据
  • 列表操作方法用错:循环内每次调用assignAll会直接覆盖列表之前的内容,就算取值正确,最终IndicatorsChecklist里也只会存最后一个外层分类下的内层指标,拿不到全量数据
修复代码

先确认模型定义:Indicatorslist是外层指标分类的响应式列表,每个分类项下的indicators字段是对应分类下的具体指标对象列表,IndicatorsChecklist是存储全量内层指标的响应式列表,修复后的代码如下:

void fetchAllIndicatorsList(int ModuleId) async {
  try {
    isLoading(true);
    final responseData = await DioClient.fetchAllIndicators(ModuleId);
    if (responseData != null) {
      // 清空历史缓存数据
      Indicatorslist.clear();
      IndicatorsChecklist.clear();
      // 赋值外层分类列表
      Indicatorslist.value = responseData;

      // 修正循环条件,遍历所有外层分类
      for (var i = 0; i < Indicatorslist.length; i++) {
        final currentCategory = Indicatorslist[i];
        // 做空安全判断,避免空指针异常
        if (currentCategory.indicators != null && currentCategory.indicators!.isNotEmpty) {
          // 追加内层完整指标对象,不要取长度值
          IndicatorsChecklist.addAll(currentCategory.indicators!);
        }
      }
    }
  } finally {
    isLoading(false);
  }
}
额外注意事项
  • 如果DioClient.fetchAllIndicators返回的是接口原始JSON Map、没有做模型序列化,需要先把内层indicators对应的JSON数组转成对应的Dart模型对象再塞进列表,否则拿到的会是动态类型的Map集合,不是类型安全的模型实例
  • GetX响应式列表的assignAll方法会全量替换列表原有内容,addAll是在现有列表基础上追加内容,如果业务是要做分类分组展示,不要把所有内层指标拍平塞进同一个列表,要按分类维度单独存储内层列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:39:19