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

Flutter/Dart报RangeError,为何判断索引值为null会触发该错误?

错误原因分析

你遇到的RangeError (index): Invalid value. Valid value range is empty: 0报错,本质是数组越界访问,具体触发逻辑如下:

  • Dart中访问List的指定索引时,会先做合法校验:如果访问的索引大于等于List的当前长度,会直接抛出RangeError,不会进入后续的null判断逻辑。你当前代码运行时password是长度为0的空列表,执行password[0]这个访问动作的瞬间就触发了越界,还没执行== null的比较逻辑。
  • 你的原有判断逻辑隐含了「password至少存在索引为0的元素,只是该元素可能为null」的前提,但实际运行时这个前提不成立,password还没有存入任何元素,是个空数组。
修复方案

你需要先判断数组长度合法之后,再访问对应索引的元素,可选写法如下:

  1. 先判断数组非空,再访问索引
Icon(
  password.isNotEmpty && password[0] == null ? unchangedPassword : changedPassword,
  color: Colors.white,
  size: 20,
)
  1. 用Dart 3.0+提供的安全访问方法elementAtOrNull,索引不存在时直接返回null,不会抛出越界错误
Icon(
  password.elementAtOrNull(0) == null ? unchangedPassword : changedPassword,
  color: Colors.white,
  size: 20,
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 05:42:02