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

Flutter嵌套列表(List<List<Product>>)索引获取错误问题排查

嵌套分页列表中查找指定元素索引的问题

场景说明

存在分页机制,每页包含10个Product,当一页填满10个数据时会传入新的列表,数据结构为:

List<List<Product>>

需求

检查该嵌套列表中是否存在指定pid的Product,若存在则获取其外层列表的索引与内层列表的索引(例:确认pid为35的Product在外层第0个列表的第4个位置)。

当前实现

使用以下代码,但无法正确获取索引:

for (var lists in _allPagedResults) {
          exists = lists.any((result) => result.pid == id);
          index = lists.indexWhere((result) => result.pid == id);
          if (exists == true) {
            break;
          }
        }
        if (exists == true) {
          if (index != 0) {
            observerController.animateTo(
              index: _allPagedResults.length <= _productLimit
                  ? index
                  : _allPagedResults.length * _productLimit + index,
              duration: const Duration(milliseconds: 250),
              curve: Curves.ease,
            );
          }
        } else {
          _requestProduct(true, id);
        }

问题

当前代码无法正确获取目标元素的外层和内层索引,求解决方案。


解决方案

问题根源

  1. 原循环使用for-in遍历,未记录外层列表的索引,即使找到目标元素,也无法确定它属于哪一页(外层列表)
  2. 全局位置的计算逻辑错误,原代码的公式不符合分页数据的位置规则

修正代码

int outerPageIndex = -1;
int innerItemIndex = -1;
bool isExists = false;

// 遍历外层列表,同时追踪外层索引
for (int i = 0; i < _allPagedResults.length; i++) {
  final currentPage = _allPagedResults[i];
  innerItemIndex = currentPage.indexWhere((product) => product.pid == id);
  if (innerItemIndex != -1) {
    outerPageIndex = i;
    isExists = true;
    break;
  }
}

if (isExists) {
  // 计算正确的全局索引:页索引*每页数量 + 页内元素索引
  final globalPosition = outerPageIndex * 10 + innerItemIndex;
  if (globalPosition != 0) {
    observerController.animateTo(
      index: globalPosition,
      duration: const Duration(milliseconds: 250),
      curve: Curves.ease,
    );
  }
} else {
  _requestProduct(true, id);
}

代码说明

  • 改用带索引的for循环,直接获取外层列表的索引i,避免丢失页信息
  • 利用indexWhere的返回值(找不到返回-1)判断是否找到目标,无需额外调用any(),减少一次遍历
  • 全局位置计算采用页索引*10 + 页内索引,完全符合分页数据的位置逻辑
  • 变量命名更清晰,区分页索引和元素索引,避免混淆

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:05:32