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

Dart开发:列表移除指定值元素后如何获取对应位置的下一个索引值

实现方案

你可以按以下两种场景选择实现方式,核心逻辑是先计算原索引在删除元素后的偏移量,避免索引错乱:

场景1:需要保留删除后的完整列表,通用适配任意场景

void main() {
  final numbers = [1,2,3,4,5];
  // 把生成的可迭代对象转为可索引的List
  final originalList = List.generate(numbers.length,
    (i) => numbers.sublist(0, i + 1)).expand((i) => i).toList();
  const targetRemoveValue = 3;
  const originalIndex = 5;

  // 统计原索引位置之前有多少个要删除的元素,计算原索引在新列表中的对应位置
  int removeCountBefore = originalList.sublist(0, originalIndex)
      .where((e) => e == targetRemoveValue)
      .length;
  int newIndex = originalIndex - removeCountBefore;

  // 移除所有目标值得到新列表
  final newList = originalList.where((e) => e != targetRemoveValue).toList();

  // 取原索引对应位置的下一个元素,增加越界判断避免报错
  if (newIndex + 1 < newList.length) {
    print(newList[newIndex + 1]); // 输出结果:1
  }
}

场景2:不需要保留原列表,追求极简写法

如果你的业务场景不需要保留原始生成的列表,也不需要兼容其他索引位置的通用查询,可以直接简化写法:

void main() {
  final numbers = [1,2,3,4,5];
  final list = List.generate(numbers.length,
    (i) => numbers.sublist(0, i + 1)).expand((i) => i).toList();
  // 直接删除所有值为3的元素
  list.removeWhere((e) => e == 3);
  // 原索引5之前没有值为3的元素,删除后对应位置不变,取索引5的元素即可
  print(list[5]); // 输出结果:1
}

逻辑说明

删除列表元素时,所有位于被删元素之后的索引都会统一前移1位,所以只要先统计目标原索引之前有多少个被删除的元素,就能准确定位到原索引在新列表中的位置,这个逻辑是通用的,可适配任意要删除的值和原索引位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:57:01