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

Flutter中RangeError(length)报错:已判空仍出现空值问题

问题描述

Firebase Crashlytics上报了如下致命错误:

Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: RangeError (length): Invalid value: Valid value range is empty: 0. Error thrown null.

报错代码行:

if (dateList1[0]==""||dateList1[0]==null){

相关代码片段:

var dateList1;

int indexToRemove = 0;

List newList = dateList0.where((x) => dateList0.indexOf(x) != 
indexToRemove).toList();

dateList1=newList;

if (dateList1[0]==""||dateList1[0]==null){

提问者已对dateList1[0]做了空值判断,但仍触发错误,询问原因。

问题原因及解决方案
  • 核心原因:你只判断了dateList1[0]是否为空或null,但忽略了dateList1本身可能是空列表的情况。当dateList0原本只有1个元素时,执行where过滤掉索引0的元素后,newList(即dateList1)会变成空列表,此时访问dateList1[0]就会触发RangeError——空列表没有索引0的元素。

  • 解决方案:

    1. 先判断列表非空,再访问索引0:
      if (dateList1.isNotEmpty && (dateList1[0] == "" || dateList1[0] == null)) {
        // 你的业务逻辑
      }
      
    2. 或者使用空安全的firstOrNull避免直接访问索引:
      if (dateList1.firstOrNull == "" || dateList1.firstOrNull == null) {
        // 你的业务逻辑
      }
      
    3. 原代码的过滤逻辑有隐患:如果dateList0存在重复元素,indexOf会返回第一个匹配项的索引,导致错误过滤多个重复元素。如果只是想移除索引0的元素,更安全的写法是:
      List newList = List.from(dateList0);
      if (newList.isNotEmpty) {
        newList.removeAt(0);
      }
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:54:14