跳到主要內容

dart:core

dart:core 庫(API 參考)提供了一組小巧但至關重要的內建功能。此庫會自動匯入到每個 Dart 程式中。

列印到控制檯

#

頂級的 print() 方法接受單個引數(任何 Object),並在控制檯中顯示該物件的字串值(透過 toString() 返回)。

dart
print(anObject);
print('I drink $tea.');

有關基本字串和 toString() 的更多資訊,請參閱語言概覽中的字串部分。

數字

#

dart:core 庫定義了 num、int 和 double 類,這些類提供了一些用於處理數字的基本實用功能。

你可以使用 int 和 double 的 parse() 方法將字串分別轉換為整數或雙精度浮點數

dart
assert(int.parse('42') == 42);
assert(int.parse('0x42') == 66);
assert(double.parse('0.50') == 0.5);

或者使用 num 的 parse() 方法,該方法如果可能則建立一個整數,否則建立一個雙精度浮點數

dart
assert(num.parse('42') is int);
assert(num.parse('0x42') is int);
assert(num.parse('0.50') is double);

要指定整數的基數,請新增一個 radix 引數

dart
assert(int.parse('42', radix: 16) == 66);

使用 toString() 方法將 int 或 double 轉換為字串。要指定小數點右側的位數,請使用 toStringAsFixed()。要指定字串中的有效位數,請使用 toStringAsPrecision():

dart
// Convert an int to a string.
assert(42.toString() == '42');

// Convert a double to a string.
assert(123.456.toString() == '123.456');

// Specify the number of digits after the decimal.
assert(123.456.toStringAsFixed(2) == '123.46');

// Specify the number of significant figures.
assert(123.456.toStringAsPrecision(2) == '1.2e+2');
assert(double.parse('1.2e+2') == 120.0);

有關更多資訊,請參閱 int、 double、num 的 API 文件。另請參閱 dart:math 部分

字串與正則表示式

#

Dart 中的字串是不可變的 UTF-16 程式碼單元序列。語言概覽中有更多關於字串的資訊。你可以使用正則表示式(RegExp 物件)在字串中搜索和替換字串的一部分。

String 類定義了 split()contains()startsWith()endsWith() 等方法。

在字串中搜索

#

你可以在字串中找到特定位置,以及檢查字串是否以特定模式開頭或結尾。例如

dart
// Check whether a string contains another string.
assert('Never odd or even'.contains('odd'));

// Does a string start with another string?
assert('Never odd or even'.startsWith('Never'));

// Does a string end with another string?
assert('Never odd or even'.endsWith('even'));

// Find the location of a string inside a string.
assert('Never odd or even'.indexOf('odd') == 6);

從字串中提取資料

#

你可以分別將字串中的單個字元作為 Strings 或 ints 獲取。確切地說,你實際獲取的是單個 UTF-16 程式碼單元;高位字元,如高音譜號符號 ('\u{1D11E}'),每個由兩個程式碼單元組成。

你還可以提取子字串或將字串拆分為子字串列表

dart
// Grab a substring.
assert('Never odd or even'.substring(6, 9) == 'odd');

// Split a string using a string pattern.
var parts = 'progressive web apps'.split(' ');
assert(parts.length == 3);
assert(parts[0] == 'progressive');

// Get a UTF-16 code unit (as a string) by index.
assert('Never odd or even'[0] == 'N');

// Use split() with an empty string parameter to get
// a list of all characters (as Strings); good for
// iterating.
for (final char in 'hello'.split('')) {
  print(char);
}

// Get all the UTF-16 code units in the string.
var codeUnitList = 'Never odd or even'.codeUnits.toList();
assert(codeUnitList[0] == 78);

::: 在許多情況下,你希望處理 Unicode 字形簇而不是純程式碼單元。這些是使用者感知的字元(例如,“🇬🇧”是一個使用者感知的字元,但由多個 UTF-16 程式碼單元組成)。為此,Dart 團隊提供了 characters 包。 ::

轉換為大寫或小寫

#

你可以輕鬆地將字串轉換為大寫和小寫形式

dart
// Convert to uppercase.
assert('web apps'.toUpperCase() == 'WEB APPS');

// Convert to lowercase.
assert('WEB APPS'.toLowerCase() == 'web apps');

去除空白符和空字串

#

使用 trim() 去除所有前導和尾隨的空白字元。要檢查字串是否為空(長度為零),請使用 isEmpty

dart
// Trim a string.
assert('  hello  '.trim() == 'hello');

// Check whether a string is empty.
assert(''.isEmpty);

// Strings with only white space are not empty.
assert('  '.isNotEmpty);

替換字串的一部分

#

字串是不可變物件,這意味著你可以建立它們但不能更改它們。如果你仔細檢視 String API 參考,你會注意到沒有任何方法實際上改變了 String 的狀態。例如,replaceAll() 方法會返回一個新的 String,而不會改變原始 String

dart
var greetingTemplate = 'Hello, NAME!';
var greeting = greetingTemplate.replaceAll(RegExp('NAME'), 'Bob');

// greetingTemplate didn't change.
assert(greeting != greetingTemplate);

構建字串

#

要以程式設計方式生成字串,可以使用 StringBuffer。StringBuffer 不會生成新的 String 物件,直到呼叫 toString()writeAll() 方法有一個可選的第二個引數,允許你指定分隔符——在本例中是空格。

dart
var sb = StringBuffer();
sb
  ..write('Use a StringBuffer for ')
  ..writeAll(['efficient', 'string', 'creation'], ' ')
  ..write('.');

var fullString = sb.toString();

assert(fullString == 'Use a StringBuffer for efficient string creation.');

正則表示式

#

RegExp 類提供了與 JavaScript 正則表示式相同的功能。使用正則表示式進行高效的字串搜尋和模式匹配。

dart
// Here's a regular expression for one or more digits.
var digitSequence = RegExp(r'\d+');

var lettersOnly = 'llamas live fifteen to twenty years';
var someDigits = 'llamas live 15 to 20 years';

// contains() can use a regular expression.
assert(!lettersOnly.contains(digitSequence));
assert(someDigits.contains(digitSequence));

// Replace every match with another string.
var exedOut = someDigits.replaceAll(digitSequence, 'XX');
assert(exedOut == 'llamas live XX to XX years');

你也可以直接使用 RegExp 類。Match 類提供了對正則表示式匹配的訪問。

dart
var digitSequence = RegExp(r'\d+');
var someDigits = 'llamas live 15 to 20 years';

// Check whether the reg exp has a match in a string.
assert(digitSequence.hasMatch(someDigits));

// Loop through all matches.
for (final match in digitSequence.allMatches(someDigits)) {
  print(match.group(0)); // 15, then 20
}

更多資訊

#

有關完整的方法列表,請參閱 String API 參考。另請參閱 StringBuffer、 Pattern、 RegExp、Match 的 API 參考。

集合

#

Dart 附帶了核心集合 API,其中包括列表、集合和 Map 的類。

列表

#

正如語言概覽所示,你可以使用字面量來建立和初始化列表。或者,可以使用其中一個 List 建構函式。List 類還定義了幾個用於向列表新增和從列表移除專案的方法。

dart
// Create an empty list of strings.
var grains = <String>[];
assert(grains.isEmpty);

// Create a list using a list literal.
var fruits = ['apples', 'oranges'];

// Add to a list.
fruits.add('kiwis');

// Add multiple items to a list.
fruits.addAll(['grapes', 'bananas']);

// Get the list length.
assert(fruits.length == 5);

// Remove a single item.
var appleIndex = fruits.indexOf('apples');
fruits.removeAt(appleIndex);
assert(fruits.length == 4);

// Remove all elements from a list.
fruits.clear();
assert(fruits.isEmpty);

// You can also create a List using one of the constructors.
var vegetables = List.filled(99, 'broccoli');
assert(vegetables.every((v) => v == 'broccoli'));

使用 indexOf() 查詢列表中物件的索引

dart
var fruits = ['apples', 'oranges'];

// Access a list item by index.
assert(fruits[0] == 'apples');

// Find an item in a list.
assert(fruits.indexOf('apples') == 0);

使用 sort() 方法對列表進行排序。你可以提供一個比較兩個物件的排序函式。該排序函式必須對較小的值返回 < 0,對相同的值返回 0,對較大的值返回 > 0。以下示例使用了 Comparable 定義並由 String 實現的 compareTo() 方法。

dart
var fruits = ['bananas', 'apples', 'oranges'];

// Sort a list.
fruits.sort((a, b) => a.compareTo(b));
assert(fruits[0] == 'apples');

列表是引數化型別(泛型),因此你可以指定列表應該包含的型別

dart
// This list should contain only strings.
var fruits = <String>[];

fruits.add('apples');
var fruit = fruits[0];
assert(fruit is String);
✗ 靜態分析:失敗dart
fruits.add(5); // Error: 'int' can't be assigned to 'String'

有關完整的方法列表,請參閱 List API 參考

集合 (Set)

#

Dart 中的集合 (Set) 是一個無序的唯一項集合。由於集合是無序的,你無法透過索引(位置)獲取集合中的專案。

dart
// Create an empty set of strings.
var ingredients = <String>{};

// Add new items to it.
ingredients.addAll(['gold', 'titanium', 'xenon']);
assert(ingredients.length == 3);

// Adding a duplicate item has no effect.
ingredients.add('gold');
assert(ingredients.length == 3);

// Remove an item from a set.
ingredients.remove('gold');
assert(ingredients.length == 2);

// You can also create sets using
// one of the constructors.
var atomicNumbers = Set.from([79, 22, 54]);

使用 contains()containsAll() 檢查集合中是否包含一個或多個物件

dart
var ingredients = Set<String>();
ingredients.addAll(['gold', 'titanium', 'xenon']);

// Check whether an item is in the set.
assert(ingredients.contains('titanium'));

// Check whether all the items are in the set.
assert(ingredients.containsAll(['titanium', 'xenon']));

交集是一個集合,其專案同時存在於另外兩個集合中。

dart
var ingredients = Set<String>();
ingredients.addAll(['gold', 'titanium', 'xenon']);

// Create the intersection of two sets.
var nobleGases = Set.from(['xenon', 'argon']);
var intersection = ingredients.intersection(nobleGases);
assert(intersection.length == 1);
assert(intersection.contains('xenon'));

有關完整的方法列表,請參閱 Set API 參考

Map

#

Map,通常稱為字典雜湊表,是無序的鍵值對集合。Map 將鍵關聯到某個值以便輕鬆檢索。與 JavaScript 不同,Dart 物件不是 Map。

你可以使用簡潔的字面量語法或傳統的建構函式來宣告 Map

dart
// Maps often use strings as keys.
var hawaiianBeaches = {
  'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
  'Big Island': ['Wailea Bay', 'Pololu Beach'],
  'Kauai': ['Hanalei', 'Poipu'],
};

// Maps can be built from a constructor.
var searchTerms = Map();

// Maps are parameterized types; you can specify what
// types the key and value should be.
var nobleGases = Map<int, String>();

你可以使用方括號語法新增、獲取和設定 Map 中的專案。使用 remove() 從 Map 中移除一個鍵及其對應的值。

dart
var nobleGases = {54: 'xenon'};

// Retrieve a value with a key.
assert(nobleGases[54] == 'xenon');

// Check whether a map contains a key.
assert(nobleGases.containsKey(54));

// Remove a key and its value.
nobleGases.remove(54);
assert(!nobleGases.containsKey(54));

你可以從 Map 中檢索所有值或所有鍵

dart
var hawaiianBeaches = {
  'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
  'Big Island': ['Wailea Bay', 'Pololu Beach'],
  'Kauai': ['Hanalei', 'Poipu'],
};

// Get all the keys as an unordered collection
// (an Iterable).
var keys = hawaiianBeaches.keys;

assert(keys.length == 3);
assert(Set.from(keys).contains('Oahu'));

// Get all the values as an unordered collection
// (an Iterable of Lists).
var values = hawaiianBeaches.values;
assert(values.length == 3);
assert(values.any((v) => v.contains('Waikiki')));

要檢查 Map 是否包含某個鍵,請使用 containsKey()。由於 Map 中的值可以為 null,因此不能僅透過獲取鍵的值並檢查是否為 null 來確定鍵是否存在。

dart
var hawaiianBeaches = {
  'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
  'Big Island': ['Wailea Bay', 'Pololu Beach'],
  'Kauai': ['Hanalei', 'Poipu'],
};

assert(hawaiianBeaches.containsKey('Oahu'));
assert(!hawaiianBeaches.containsKey('Florida'));

當你想僅在 Map 中不存在某個鍵時為其賦值,請使用 putIfAbsent() 方法。你必須提供一個返回值的函式。

dart
var teamAssignments = <String, String>{};
teamAssignments.putIfAbsent('Catcher', () => pickToughestKid());
assert(teamAssignments['Catcher'] != null);

有關完整的方法列表,請參閱 Map API 參考

常用集合方法

#

List、Set 和 Map 共享許多集合中常見的功能。List 和 Set 實現了其中的一些常見功能,這些功能由 Iterable 類定義。

使用 isEmptyisNotEmpty 檢查列表、集合或 Map 是否包含專案

dart
var coffees = <String>[];
var teas = ['green', 'black', 'chamomile', 'earl grey'];
assert(coffees.isEmpty);
assert(teas.isNotEmpty);

要將函式應用於列表、集合或 Map 中的每個專案,可以使用 forEach()

dart
var teas = ['green', 'black', 'chamomile', 'earl grey'];

teas.forEach((tea) => print('I drink $tea'));

當你在 Map 上呼叫 forEach() 時,你的函式必須接受兩個引數(鍵和值)

dart
hawaiianBeaches.forEach((k, v) {
  print('I want to visit $k and swim at $v');
  // I want to visit Oahu and swim at
  // [Waikiki, Kailua, Waimanalo], etc.
});

Iterables 提供了 map() 方法,該方法將所有結果組合到一個物件中

dart
var teas = ['green', 'black', 'chamomile', 'earl grey'];

var loudTeas = teas.map((tea) => tea.toUpperCase());
loudTeas.forEach(print);

要強制你的函式立即在每個專案上呼叫,請使用 map().toList()map().toSet()

dart
var loudTeas = teas.map((tea) => tea.toUpperCase()).toList();

使用 Iterable 的 where() 方法獲取所有符合條件的項。使用 Iterable 的 any()every() 方法檢查部分或所有項是否符合條件。

dart
var teas = ['green', 'black', 'chamomile', 'earl grey'];

// Chamomile is not caffeinated.
bool isDecaffeinated(String teaName) => teaName == 'chamomile';

// Use where() to find only the items that return true
// from the provided function.
var decaffeinatedTeas = teas.where((tea) => isDecaffeinated(tea));
// or teas.where(isDecaffeinated)

// Use any() to check whether at least one item in the
// collection satisfies a condition.
assert(teas.any(isDecaffeinated));

// Use every() to check whether all the items in a
// collection satisfy a condition.
assert(!teas.every(isDecaffeinated));

有關完整的方法列表,請參閱 Iterable API 參考,以及 List、 Set、Map 的 API 參考。

URI

#

Uri 類提供了用於對 URI(你可能稱之為 URL)中的字串進行編碼和解碼的函式。這些函式處理對 URI 來說是特殊字元(例如 &=)。Uri 類還會解析並公開 URI 的組成部分——主機、埠、方案等。

編碼和解碼完整的 URI

#

要對字元進行編碼和解碼,除了那些在 URI 中具有特殊含義的字元(例如 /:&#),請使用 encodeFull()decodeFull() 方法。這些方法適用於編碼或解碼完整的 URI,同時保留特殊的 URI 字元。

dart
var uri = 'https://example.org/api?foo=some message';

var encoded = Uri.encodeFull(uri);
assert(encoded == 'https://example.org/api?foo=some%20message');

var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);

注意只有 somemessage 之間的空格被編碼了。

編碼和解碼 URI 元件

#

要對字串中所有在 URI 中具有特殊含義的字元進行編碼和解碼,包括(但不限於)/&:,請使用 encodeComponent()decodeComponent() 方法。

dart
var uri = 'https://example.org/api?foo=some message';

var encoded = Uri.encodeComponent(uri);
assert(
  encoded == 'https%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message',
);

var decoded = Uri.decodeComponent(encoded);
assert(uri == decoded);

注意每個特殊字元都被編碼了。例如,/ 被編碼為 %2F

解析 URI

#

如果你有一個 Uri 物件或一個 URI 字串,你可以使用 Uri 的欄位(例如 path)獲取其組成部分。要從字串建立 Uri,請使用靜態方法 parse()

dart
var uri = Uri.parse('https://example.org:8080/foo/bar#frag');

assert(uri.scheme == 'https');
assert(uri.host == 'example.org');
assert(uri.path == '/foo/bar');
assert(uri.fragment == 'frag');
assert(uri.origin == 'https://example.org:8080');

有關你可以獲取的更多 URI 元件,請參閱 Uri API 參考

構建 URI

#

你可以使用 Uri() 建構函式從各個部分構建 URI

dart
var uri = Uri(
  scheme: 'https',
  host: 'example.org',
  path: '/foo/bar',
  fragment: 'frag',
  queryParameters: {'lang': 'dart'},
);
assert(uri.toString() == 'https://example.org/foo/bar?lang=dart#frag');

如果你不需要指定片段,要建立一個使用 http 或 https 方案的 URI,可以改為使用工廠建構函式 Uri.httpUri.https

dart
var httpUri = Uri.http('example.org', '/foo/bar', {'lang': 'dart'});
var httpsUri = Uri.https('example.org', '/foo/bar', {'lang': 'dart'});

assert(httpUri.toString() == 'http://example.org/foo/bar?lang=dart');
assert(httpsUri.toString() == 'https://example.org/foo/bar?lang=dart');

日期和時間

#

DateTime 物件代表時間點。時區可以是 UTC 或本地時區。

你可以使用多種建構函式和方法建立 DateTime 物件

dart
// Get the current date and time.
var now = DateTime.now();

// Create a new DateTime with the local time zone.
var y2k = DateTime(2000); // January 1, 2000

// Specify the month and day.
y2k = DateTime(2000, 1, 2); // January 2, 2000

// Specify the date as a UTC time.
y2k = DateTime.utc(2000); // 1/1/2000, UTC

// Specify a date and time in ms since the Unix epoch.
y2k = DateTime.fromMillisecondsSinceEpoch(946684800000, isUtc: true);

// Parse an ISO 8601 date in the UTC time zone.
y2k = DateTime.parse('2000-01-01T00:00:00Z');

// Create a new DateTime from an existing one, adjusting just some properties:
var sameTimeLastYear = now.copyWith(year: now.year - 1);

日期的 millisecondsSinceEpoch 屬性返回自“Unix 紀元”(1970 年 1 月 1 日 UTC)以來的毫秒數

dart
// 1/1/2000, UTC
var y2k = DateTime.utc(2000);
assert(y2k.millisecondsSinceEpoch == 946684800000);

// 1/1/1970, UTC
var unixEpoch = DateTime.utc(1970);
assert(unixEpoch.millisecondsSinceEpoch == 0);

使用 Duration 類計算兩個日期之間的差值,並向前或向後調整日期

dart
var y2k = DateTime.utc(2000);

// Add one year.
var y2001 = y2k.add(const Duration(days: 366));
assert(y2001.year == 2001);

// Subtract 30 days.
var december2000 = y2001.subtract(const Duration(days: 30));
assert(december2000.year == 2000);
assert(december2000.month == 12);

// Calculate the difference between two dates.
// Returns a Duration object.
var duration = y2001.difference(y2k);
assert(duration.inDays == 366); // y2k was a leap year.

有關完整的方法列表,請參閱 DateTimeDuration 的 API 參考。

實用類

#

核心庫包含各種實用類,可用於排序、對映值和迭代。

比較物件

#

實現 Comparable 介面表示一個物件可以與另一個物件進行比較,通常用於排序。compareTo() 方法對較小的值返回 < 0,對相同的值返回 0,對較大的值返回 > 0。

dart
class Line implements Comparable<Line> {
  final int length;
  const Line(this.length);

  @override
  int compareTo(Line other) => length - other.length;
}

void main() {
  var short = const Line(1);
  var long = const Line(100);
  assert(short.compareTo(long) < 0);
}

實現 Map 鍵

#

Dart 中的每個物件都會自動提供一個整數雜湊碼,因此可以用作 Map 中的鍵。但是,你可以重寫 hashCode getter 來生成自定義雜湊碼。如果你這樣做,你可能還需要重寫 == 運算子。相等的物件(透過 ==)必須具有相同的雜湊碼。雜湊碼不必是唯一的,但應該分佈均勻。

dart
class Person {
  final String firstName, lastName;

  Person(this.firstName, this.lastName);

  // Override hashCode using the static hashing methods
  // provided by the `Object` class.
  @override
  int get hashCode => Object.hash(firstName, lastName);

  // You should generally implement operator `==` if you
  // override `hashCode`.
  @override
  bool operator ==(Object other) {
    return other is Person &&
        other.firstName == firstName &&
        other.lastName == lastName;
  }
}

void main() {
  var p1 = Person('Bob', 'Smith');
  var p2 = Person('Bob', 'Smith');
  var p3 = 'not a person';
  assert(p1.hashCode == p2.hashCode);
  assert(p1 == p2);
  assert(p1 != p3);
}

迭代

#

IterableIterator 類支援對值集合進行順序訪問。要練習使用這些集合,請遵循可迭代集合教程

如果你建立一個可以為 for-in 迴圈提供 Iterator 的類,請繼承(如果可能)或實現 Iterable。實現 Iterator 以定義實際的迭代能力。

dart
class Process {
  // Represents a process...
}

class ProcessIterator implements Iterator<Process> {
  @override
  Process get current => ...
  @override
  bool moveNext() => ...
}

// A mythical class that lets you iterate through all
// processes. Extends a subclass of [Iterable].
class Processes extends IterableBase<Process> {
  @override
  final Iterator<Process> iterator = ProcessIterator();
}

void main() {
  // Iterable objects can be used with for-in.
  for (final process in Processes()) {
    // Do something with the process.
  }
}

異常

#

Dart 核心庫定義了許多常見的異常和錯誤。異常是被視為可以提前計劃和捕獲的條件。錯誤是你不期望或不計劃的條件。

兩個最常見的錯誤是

NoSuchMethodError
當接收物件(可能是 null)未實現某個方法時丟擲。
ArgumentError
當方法遇到意外引數時可能丟擲。

丟擲應用程式特定的異常是指示發生錯誤的常見方式。你可以透過實現 Exception 介面來定義自定義異常

dart
class FooException implements Exception {
  final String? msg;

  const FooException([this.msg]);

  @override
  String toString() => msg ?? 'FooException';
}

有關更多資訊,請參閱異常(在語言概覽中)和 Exception API 參考。

弱引用與終結器

#

Dart 是一種垃圾回收語言,這意味著任何未被引用的 Dart 物件都可以被垃圾回收器處理。在某些涉及原生資源或目標物件無法修改的場景中,這種預設行為可能不受歡迎。

一個 WeakReference 儲存對目標物件的引用,該引用不影響垃圾回收器對其的回收。另一種選擇是使用 Expando 為物件新增屬性。

可以使用 Finalizer 在物件不再被引用後執行回撥函式。但是,不保證此回撥一定會被執行。

一個 NativeFinalizer 為使用 dart:ffi 與原生程式碼互動提供了更強的保證;在物件不再被引用後,它的回撥至少會被呼叫一次。此外,它還可以用於關閉原生資源,例如資料庫連線或開啟的檔案。

為了確保物件不會過早地被垃圾回收和終結,類可以實現 Finalizable 介面。當局部變數是 Finalizable 時,它不會被垃圾回收,直到宣告它的程式碼塊退出。