flutter 范围错误(索引):无效值,有效值范围为空:0

uinbv5nw  于 2022-11-25  发布在  Flutter
关注(0)|答案(3)|浏览(201)
Row(         
   mainAxisAlignment: MainAxisAlignment.center,
       
   children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Icon(
                  password[0] == null ? unchangedPassword : changedPassword, //Error happens here
                  color: Colors.white,
                  size: 20,
             ),
        )
    ]
)

有人能解释一下为什么我不能写一个if语句来检查索引处的值是否等于空值吗?

xyhw6mcr

xyhw6mcr1#

使用password.isEmpty代替password[0] == null

b1uwtaje

b1uwtaje2#

密码[0]不存在。密码似乎是列表
如果它是一个Map,你可以用password[0] == null,但它不是。它是一个列表。这个值不存在。它不是null。它不存在。所以它崩溃了。
为什么它不存在?因为内存没有被分配。Flutter会在你需要的时候自动分配内存。如果你执行password.add(value),那么password[0]会在那个时候存在。但是因为你得到了范围错误,所以你没有使用password.add
对于列表,请使用password.isNotEmpty或password.length == 0;

7jmck4yq

7jmck4yq3#

我也一直面临这个问题,下面的检查解决了我的问题

Text("${(subjects.isEmpty) ? "" : subjects.name}"),

相关问题