List的官方API文檔:
https://api.dart.cn/stable/2.13.4/dart-core/List-class.html
List<E> class
:可變集合,使用[]初始化酿秸。同時文檔建議犁河,使用filled方法進行初始化省古,其中growable參數(shù)代表是否可擴展钾菊。
基本使用:
dart-增刪改查.png
通過設置length可以清空集合:
清空集合.png
其他初始化方式:
List.empty()厦幅,默認growable=false,創(chuàng)建一個長度固定的空數(shù)組
var list = List.empty();
print(list.length);//0
list.add(0);//報錯
List<E>.general芯勘,filled的加強版:允許通過一些函數(shù)初始化數(shù)據(jù)元素
general.png
List<E>.from(Iterable elements,{bool growable = true}):
第一個參數(shù)是迭代器缰犁,通過一個集合到另一個集合
void main() {
List fruit1 = ["apple","pear","peach", "banana"];
List fruit2 = List.from(fruit1.where((it) => it.length>4));
print(fruit1);//[apple, pear, peach, banana]
print(fruit2);//[apple, peach, banana]
}
List<E>.of(Iterable<E> elements,{bool growable = true}):
與List<E>.from相比,迭代器參數(shù)添加了泛型捡偏,其他作用幾乎完全一致唤冈,二者的區(qū)別是
List<String> foo = new List.from(<int>[1, 2, 3]); // 運行時報錯
List<String> bar = new List.of(<int>[1, 2, 3]); // 編譯報錯
推薦使用List<E>.of方式,Drat2更傾向于強類型語言银伟,未來from方式可能會被淘汰你虹。參考 https://stackoverflow.com/questions/50320220/in-dart-whats-the-difference-between-list-from-and-of-and-between-map-from-a
List<E>.unmodifiable(Iterable elements):創(chuàng)建一個無法改變的集合
void main() {
List fruit1 = ["apple","pear","peach", "banana"];
List fruit2 = List.unmodifiable(fruit1);
fruit2.remove("apple");//Uncaught Error: Unsupported operation: remove
}