Flutter/Dart - 集合類(lèi)型List、Map詳解

List詳解,List里面常用的屬性和方法

List的定義

  • 第一種定義方法
List myList = ['1', '2', '3'];
print(myList);
  • 第二種定義方法
var list = new List();
list.add(1);
list.add(2);
list.add(3);
print(list);

List里面的方法屬性

  • List里面的屬性
print(list.length);
print(list.isEmpty);//判斷數(shù)組是否為空
print(list.isNotEmpty);//判斷數(shù)組是否為空

print(list.reversed);// 對(duì)列表倒序排序
  • List里面的方法
List myList = ['1', '2', '3'];
//添加
myList.add('4');
print(myList); //1,2,3,4

myList.addAll(['5', '6']);
print(myList); //1,2,3,4,5,6

// 查找
print(myList.indexOf('7')); //-1
print(myList.indexOf('1')); //0

// 刪除
myList.remove('1');
print(myList); //,2,3,4,5,6
myList.removeAt(0); //參數(shù)為索引值í
print(myList); //3,4,5,6

// 修改
myList.fillRange(1, 2, 'a');
print(myList); //3,a,a,6

// 指定位置插入
myList.insert(1, 'b');
print(myList); //3,b,a,a,6
myList.insertAll(1, ['b', 'c']);
print(myList); //3,b,c,b,a,a,6

// 轉(zhuǎn)換
var str = myList.join('-');
print(str); //3-b-c-b-a-a-6

var list = str.split('-');
print(list); //3,b,c,b,a,a,6

Set定義集合

  • set是沒(méi)有順序且不能重復(fù)的集合,所以不能通過(guò)索引去獲取值
  • 可以用來(lái)去除數(shù)組重復(fù)內(nèi)容
var s = new Set();
s.add(1);
s.add(2);
print(s);// {1,2}
print(s.toList());// [1,2]

數(shù)組去重

List myList2 = [1, 2, 4, 3, 2, 3, 23];
var s = new Set();
s.addAll(myList2);
print(s.toList());

Map詳解,Map里面常用屬性和方法

Map的定義
第一種定義方式

var person = {
  "name": "張三",
  "age": 20,
};

第二種定義方式

var person2 = new Map();
person2["name"] = "李四";

Map的屬性

print(person.keys.toList()); //[name,age]
print(person.values.toList()); //['張三', 20]
print(person.isEmpty);
print(person.isNotEmpty);

Map的方法

// 添加屬性
person.addAll({
  "work": ['程序員', '外貿(mào)專(zhuān)家'],
  "height": 180,
});

// 移除屬性
person.remove("work");
// 是否包含某個(gè)值
person.containsValue("張三");
// 是否包含某個(gè)key
person.containsKey("work");
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容