可變列表可以在運行時動態增長。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]