可变列表可以在运行时动态增长。List.add()
函数将指定的值附加到List
的末尾并返回修改后的List
对象。参考以下示例 -
void main() {
List l = [1,2,3];
l.add(12);
print(l);
}
它将产生以下输出 -
[1, 2, 3, 12]
List.addAll()
函数接受以逗号分隔的多个值,并将这些值附加到List
。
void main() {
List l = [1,2,3];
l.addAll([12,13]);
print(l);
}
它将产生以下输出 -
[1, 2, 3, 12, 13]
List.addAll()
函数接受以逗号分隔的多个值,并将这些值附加到List
。
void main() {
List l = [1,2,3];
l.addAll([12,13]);
print(l);
}
它将产生以下输出 -
[1, 2, 3, 12, 13]
Dart还支持在List中的特定位置添加元素。insert()
函数接受一个值并将其插入指定的索引。类似地,insertAll()
函数从指定的索引开始插入给定的值列表。insert
和insertAll
函数的语法如下 -
List.insert(index,value)
List.insertAll(index, iterable_list_of _values)
以下示例分别说明了insert()
和insertAll()
函数的用法。
语法
List.insert(index,value)
List.insertAll([Itearble])
示例:List.insert()
void main() {
List l = [1,2,3];
l.insert(0,4);
print(l);
}
执行上面示例代码,得到以下结果 -
[4, 1, 2, 3]
示例:List.insertAll()
void main() {
List l = [1,2,3];
l.insertAll(0,[120,130]);
print(l);
}
执行上面示例代码,得到以下结果 -
[120, 130, 1, 2, 3]