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

使用for循环填充多级Map时触发RangeError(index)错误求助

遍历循环中向Map存入嵌套Map时出现RangeError(index)错误

错误信息

未处理的异常:
RangeError (index): Invalid value: Valid value range is empty: 0
#0 List.[] (dart:core-patch/growable_array.dart:264:36)
#1 main (file:///X:/test/commands.dart:....)

问题描述

我在遍历整数的for循环中,尝试将Map<String, dynamic>作为值存入Map<int, Map>,触发了上述错误。改用List<Map>后,错误依然存在。

预期得到的结构:

service = { 
    0: { 'serviceName': value, 'departure': value }
}

我的代码

var trips = document.getElementsByClassName('searchresults')[0].getElementsByClassName('trip');

print(trips.length); // 输出379

var tripCount = trips.length;

print(trips[1].getElementsByClassName('schedule')[0].text.trim()); // 能正常获取serviceName字符串

Map<int, Map<String, dynamic>> services = {};

for (int i = 0; i < tripCount; i++) {
    services[i] = { 
        'serviceName': trips[i].getElementsByClassName('schedule')[0].text.trim(), 
        'departure': trips[i].getElementsByClassName('departure')[0].text.trim()
    }; 
}

问题原因及解决办法

错误本质是索引越界:虽然trips的长度是379,但不是每个trip元素都包含schedule或departure类的子元素。当某个trips[i]调用getElementsByClassName('schedule')或getElementsByClassName('departure')返回空集合时,直接访问[0]就会触发这个错误——你之前只测试了trips[1],不代表所有元素都符合预期。

修复后的代码(兼容缺失元素的情况)

var trips = document.getElementsByClassName('searchresults')[0].getElementsByClassName('trip');
var tripCount = trips.length;
Map<int, Map<String, dynamic>> services = {};

for (int i = 0; i < tripCount; i++) {
    // 先获取子元素集合,判断是否为空
    var scheduleList = trips[i].getElementsByClassName('schedule');
    var departureList = trips[i].getElementsByClassName('departure');
    
    // 确保元素存在再取值,避免索引越界
    String serviceName = scheduleList.isNotEmpty ? scheduleList[0].text.trim() : '无服务名称';
    String departure = departureList.isNotEmpty ? departureList[0].text.trim() : '无出发信息';
    
    services[i] = { 'serviceName': serviceName, 'departure': departure };
}

只保留完整信息的条目

如果不需要缺失信息的条目,可以这样写:

for (int i = 0; i < tripCount; i++) {
    var scheduleList = trips[i].getElementsByClassName('schedule');
    var departureList = trips[i].getElementsByClassName('departure');
    
    if (scheduleList.isNotEmpty && departureList.isNotEmpty) {
        services[i] = { 
            'serviceName': scheduleList[0].text.trim(), 
            'departure': departureList[0].text.trim()
        }; 
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:35:35