dart:core库中List类支持的以下函数可用于删除List中的项目。
List.remove()List.remove()
函数删除列表中第一次出现的指定项。如果成功地从列表中删除指定的值,则此函数返回true
。
语法
List.remove(Object value)
其中,
value
- 表示要从列表中删除的项的值。
以下示例显示如何使用此功能 -
void main() {
List l = [1, 2, 3,4,5,6,7,8,9];
print('The value of list before removing the list element ${l}');
bool res = l.remove(1);
print('The value of list after removing the list element ${l}');
}
它将产生以下输出 -
The value of list before removing the list element [1, 2, 3, 4, 5, 6, 7, 8, 9]
The value of list after removing the list element [2, 3, 4, 5, 6, 7, 8, 9]
List.removeAt()
List.removeAt()
函数删除指定索引处的值并返回它。
语法
List.removeAt(int index)
其中,
index
- 表示应从列表中删除的元素的索引。
以下示例显示如何使用此功能 -
void main() {
List l = [1, 2, 3,4,5,6,7,8,9];
print('The value of list before removing the list element ${l}');
dynamic res = l.removeAt(1);
print('The value of the element ${res}');
print('The value of list after removing the list element ${l}');
}
执行上面示例代码,得到以下结果 -
The value of list before removing the list element [1, 2, 3, 4, 5, 6, 7, 8, 9]
The value of the element 2
The value of list after removing the list element [1, 3, 4, 5, 6, 7, 8, 9]
List.removeLast()
List.removeLast()
函数弹出并返回List中的最后一项。语法如下 -
List.removeLast()
以下示例显示如何使用此函数 -
void main() {
List l = [1, 2, 3,4,5,6,7,8,9];
print('The value of list before removing the list element ${l}');
dynamic res = l.removeLast();
print('The value of item popped ${res}');
print('The value of list after removing the list element ${l}');
}
执行上面示例代码,得到以下结果:
The value of list before removing the list element [1, 2, 3, 4, 5, 6, 7, 8, 9]
The value of item popped 9
The value of list after removing the list element [1, 2, 3, 4, 5, 6, 7, 8]
List.removeRange()
List.removeRange()
函数删除指定范围内的项目。语法如下 -
List.removeRange(int start, int end)
其中,
start
- 表示删除项目的起始位置。end
- 表示列表中停止删除项目的位置。
以下示例显示如何使用此函数 -
void main() {
List l = [1, 2, 3,4,5,6,7,8,9];
print('The value of list before removing the list element ${l}');
l.removeRange(0,3);
print('The value of list after removing the list
element between the range 0-3 ${l}');
}
执行上面示例代码,得到以下结果:
The value of list before removing the list element
[1, 2, 3, 4, 5, 6, 7, 8, 9]
The value of list after removing the list element
between the range 0-3 [4, 5, 6, 7, 8, 9]