未捕获的错误:RangeError:值不在范围内:3
2022-12-06
81
我想从
List
中逐个删除项目。
我也可以使用
clear()
方法清除整个 List,但我不想这样做。
如果有人有解决这个问题的方法,请指出。
谢谢。
void main(){
List<String> list =['first','second','3rd','4th','5th'];
list.removeAt(0);
list.removeAt(1);
list.removeAt(2);
list.removeAt(3);
list.removeAt(4);
print(list);
// I don't want to clear all list at once
// I want to remove one by one element from the list
// list.clear();
// list.map((e){
// }).toList();
}
3个回答
删除前 3 个元素后,就不再有第 3 个元素了。您可以
list.removeAt(0);
list.removeAt(0);
list.removeAt(0);
list.removeAt(0);
list.removeAt(0);
或
list.removeAt(4);
list.removeAt(3);
list.removeAt(2);
list.removeAt(1);
list.removeAt(0);
Emre Faruk KOLAÇ
2022-12-06
删除前 3 个元素后,就不再有第 3 个元素了。要使列表长度动态变化,可以这样做:
void main() {
List<String> list = ['first','second','3rd','4th','5th'];
int length = list.length;
for (int i = 0; i < length; i++) {
list.removeAt(0);
}
print(list);
}
Marci
2022-12-06
当您使用简单的打印语句自行调试时,就会发现发生了什么:
void main(){
List<String> list =['first','second','3rd','4th','5th'];
print(list);
list.removeAt(0);
print(list);
list.removeAt(1);
print(list);
list.removeAt(2);
print(list);
list.removeAt(3);
print(list);
list.removeAt(4);
print(list);
}
[first, second, 3rd, 4th, 5th]
删除此列表的第一个元素:
[second, 3rd, 4th, 5th]
删除该列表的第二个元素:
[second, 4th, 5th]
删除该列表的第三个元素:
[second, 4th]
最后,尝试删除不再具有四个元素的列表的第四个元素:
Uncaught Error: RangeError: Value not in range: 3
nvoigt
2022-12-06