Flutter | FireStore 出现RangeError索引越界错误该如何解决?
错误原因
- 第一处逻辑错误:初始化的
userList长度仅为1,你后续尝试向索引位置1写入数据时,超出了列表的初始长度边界,这也是报错信息里「index should be less than 1: 1」的直接触发原因。 - 第二处逻辑错误:
for循环的判断条件写为i <= allData.length,列表索引从0开始计数,长度为2的allData合法索引只有0和1,当i自增到2时会触发allData的索引越界。 - 额外冗余逻辑:你代码中写的
await allData[i]['customerNumber']是多余操作,allData已经是拉取到本地内存的数据集,字段取值是同步操作不需要加await。
修复方案
- 不需要提前给
userList设置固定初始值,直接初始化为空的可增长列表即可 - 修正
for循环的判断条件为i < allData.length,也可以直接用map遍历更简洁 - 异常分支需要返回符合返回值类型要求的空列表,避免后续调用时出现类型错误
修复后代码
Future<List> getPreAppliedUserList() async { try { List userList = []; QuerySnapshot querySnapshot = await _db!.collection(_preAppliedUserCollection).get(); List allData = querySnapshot.docs.map((doc) => doc.data()).toList(); print(allData.length); /// 2 // 写法1:保留for循环的修正版本 for (int i = 0; i < allData.length; i++) { userList.add(allData[i]['customerNumber']); } // 写法2:更简洁的替代写法,可直接替换上面整个for循环 // userList = allData.map((item) => item['customerNumber']).toList(); return userList; } on FirebaseException { print("getPreAppliedUserList error"); return []; } }
内容的提问来源于stack exchange,提问作者Çağlar Binici
相关产品推荐
相关产品推荐

