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

如何在Flutter中处理Map<int, List<int>>数据并提取章节与节信息

遍历Map<int, List>列表获取章节与节位置的方法

你的数据源是**List<Map<int, List>>**类型(由多个JSON对象组成的列表),每个Map的键代表章节号,对应的值是包含节起始、结束位置的列表。以下是两种常用的遍历方式:

1. 嵌套forEach遍历

先定义你的数据列表:

List<Map<int, List<int>>> chapterData = [
  {1: [1,7], 2: [1,141]},
  {2: [142, 252]},
  {2: [253, 286], 3: [1,92]},
];

使用嵌套forEach遍历每个元素:

chapterData.forEach((mapItem) {
  mapItem.entries.forEach((entry) {
    int chapterNum = entry.key;
    int sectionStart = entry.value[0];
    int sectionEnd = entry.value[1];
    
    // 这里处理获取到的数据,比如打印或存入业务模型
    print('章节$chapterNum:节起始$sectionStart,节结束$sectionEnd');
  });
});

2. for-in循环遍历

这种方式更直观,还能方便添加边界校验:

for (var mapItem in chapterData) {
  for (var entry in mapItem.entries) {
    int chapter = entry.key;
    List<int> sectionPos = entry.value;
    
    // 校验列表长度,避免下标越界
    if (sectionPos.length == 2) {
      int start = sectionPos[0];
      int end = sectionPos[1];
      print('章节$chapter:起始$start,结束$end');
    }
  }
}

扩展:获取章节名称

如果需要将章节号转换为对应名称,可以维护一个章节映射表:

Map<int, String> chapterNameMap = {
  1: '第一章',
  2: '第二章',
  3: '第三章',
};

遍历的时候直接通过映射表获取名称:

chapterData.forEach((mapItem) {
  mapItem.entries.forEach((entry) {
    String chapterName = chapterNameMap[entry.key] ?? '未知章节${entry.key}';
    int start = entry.value[0];
    int end = entry.value[1];
    print('$chapterName:节起始$start,节结束$end');
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:57:17