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的元素。解决方案:
- 先判断列表非空,再访问索引0:
if (dateList1.isNotEmpty && (dateList1[0] == "" || dateList1[0] == null)) { // 你的业务逻辑 } - 或者使用空安全的
firstOrNull避免直接访问索引:if (dateList1.firstOrNull == "" || dateList1.firstOrNull == null) { // 你的业务逻辑 } - 原代码的过滤逻辑有隐患:如果
dateList0存在重复元素,indexOf会返回第一个匹配项的索引,导致错误过滤多个重复元素。如果只是想移除索引0的元素,更安全的写法是:List newList = List.from(dateList0); if (newList.isNotEmpty) { newList.removeAt(0); }
- 先判断列表非空,再访问索引0:
内容的提问来源于stack exchange,提问作者Nitneuq
相关产品推荐
相关产品推荐

