Dart 提供了一系列內(nèi)置類型(Built-in Types),幫助開發(fā)者進(jìn)行常見的編程任務(wù)。這些類型包括基本數(shù)據(jù)類型、集合類型和特殊類型。以下是對(duì)這些內(nèi)置類型的詳細(xì)說明:
基本數(shù)據(jù)類型
Numbers(數(shù)值類型):
int:表示整數(shù)。
int age = 30;
int hexValue = 0xDEADBEEF;
double:表示雙精度浮點(diǎn)數(shù)
Strings(字符串類型):
1、使用單引號(hào)或雙引號(hào)創(chuàng)建字符串。
String name = 'Alice';
String greeting = "Hello, World!";
2、使用三引號(hào)創(chuàng)建多行字符串
String multiline = '''
This is
a multiline
string.
''';
3、使用插值表達(dá)式 ${expression} 進(jìn)行字符串插值。
String name = 'Alice';
String message = 'Hello, ${name}!';
Booleans(布爾類型):
bool 類型表示布爾值,只有兩個(gè)取值:true 和 false。
bool isTrue = true;
bool isFalse = false;
集合類型
Lists(列表)
特點(diǎn):
1、有序:元素有索引,從 0 開始。
2、可包含重復(fù)元素。
創(chuàng)建和使用
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
List<String> fruits = ['Apple', 'Banana', 'Orange'];
// 訪問元素
print(fruits[0]); // 輸出:Apple
// 添加元素
fruits.add('Grapes');
print(fruits); // 輸出:[Apple, Banana, Orange, Grapes]
// 刪除元素
fruits.remove('Banana');
print(fruits); // 輸出:[Apple, Orange, Grapes]
// 遍歷
for (var fruit in fruits) {
print(fruit);
}
}
Sets(集合)
特點(diǎn):
1、無序,元素沒有索引
2、不包含重復(fù)元素:每個(gè)元素都是唯一的。
void main() {
Set<int> numbers = {1, 2, 3, 4, 5};
Set<String> fruits = {'Apple', 'Banana', 'Orange'};
// 添加元素
fruits.add('Grapes');
fruits.add('Apple'); // 不會(huì)添加,因?yàn)?'Apple' 已存在
print(fruits); // 輸出:{Apple, Banana, Orange, Grapes}
// 刪除元素
fruits.remove('Banana');
print(fruits); // 輸出:{Apple, Orange, Grapes}
// 檢查是否包含某個(gè)元素
print(fruits.contains('Orange')); // 輸出:true
// 遍歷
for (var fruit in fruits) {
print(fruit);
}
}
Maps 映射
特點(diǎn):
1、鍵值對(duì)存儲(chǔ):每個(gè)元素都是一個(gè)鍵值對(duì)。
2、無序:鍵值對(duì)沒有索引。
3、鍵是唯一的,但值可以重復(fù)。
void main() {
Map<String, int> scores = {
'Alice': 90,
'Bob': 85,
'Charlie': 95
};
// 訪問元素
print(scores['Alice']); // 輸出:90
// 添加或更新元素
scores['David'] = 80;
scores['Alice'] = 95; // 更新 'Alice' 的分?jǐn)?shù)
print(scores); // 輸出:{Alice: 95, Bob: 85, Charlie: 95, David: 80}
// 刪除元素
scores.remove('Bob');
print(scores); // 輸出:{Alice: 95, Charlie: 95, David: 80}
// 檢查是否包含某個(gè)鍵
print(scores.containsKey('Charlie')); // 輸出:true
// 遍歷鍵值對(duì)
scores.forEach((key, value) {
print('$key: $value');
});
}
使用建議
當(dāng)需要有序且允許重復(fù)的集合時(shí),使用 List。
當(dāng)需要唯一元素且不關(guān)心順序時(shí),使用 Set。
當(dāng)需要鍵值對(duì)且不關(guān)心順序時(shí),使用 Map。
特殊類型
Runes(符文):
符文是 Dart 字符串中的 UTF-32 字符。字符串是 UTF-16 字符的集合,因此一個(gè)符文可以表示一個(gè) Unicode 字符。
Runes input = Runes('\u{1F600}'); // ??
Symbols(符號(hào)):
符號(hào)用于標(biāo)識(shí)程序中聲明的運(yùn)算符或標(biāo)識(shí)符
Symbol libraryName = #libraryName;
Functions(函數(shù)):
Dart 中的函數(shù)也是對(duì)象,有類型 Function。這意味著可以將函數(shù)賦值給變量或作為參數(shù)傳遞。
int add(int a, int b) {
return a + b;
}
void main() {
Function operation = add;
print(operation(2, 3)); // 輸出:5
}
特殊常量
null
Dart 中的所有變量默認(rèn)值都是 null。null 是一個(gè)對(duì)象,屬于 Null 類型。
int? nullableInt;
print(nullableInt); // 輸出:null