目錄

枚舉類型

枚舉類型,通常稱為列舉枚舉,是一種特殊類別,用於表示固定數量的常數值。

宣告簡單枚舉

#

若要宣告簡單的枚舉類型,請使用 enum 關鍵字並列出您想要列舉的值

dart
enum Color { red, green, blue }

宣告增強枚舉

#

Dart 也允許枚舉宣告宣告具有欄位、方法和常數建構子的類別,這些類別僅限於固定數量的已知常數實例。

若要宣告增強的枚舉,請遵循類似於一般類別的語法,但有一些額外的要求

  • 實例變數必須是 final,包括由混入新增的變數。
  • 所有產生式建構子都必須是常數。
  • 工廠建構子只能傳回其中一個固定的已知枚舉實例。
  • 由於會自動繼承 Enum,因此無法繼承其他類別。
  • 無法覆寫 indexhashCode、等號運算子 ==
  • 在枚舉中無法宣告名為 values 的成員,因為它會與自動產生的靜態 values getter 衝突。
  • 枚舉的所有實例都必須在宣告的開頭宣告,而且必須至少宣告一個實例。

增強枚舉中的實例方法可以使用 this 來參考目前的枚舉值。

以下範例宣告具有多個實例、實例變數、getter 和實作介面的增強枚舉

dart
enum Vehicle implements Comparable<Vehicle> {
  car(tires: 4, passengers: 5, carbonPerKilometer: 400),
  bus(tires: 6, passengers: 50, carbonPerKilometer: 800),
  bicycle(tires: 2, passengers: 1, carbonPerKilometer: 0);

  const Vehicle({
    required this.tires,
    required this.passengers,
    required this.carbonPerKilometer,
  });

  final int tires;
  final int passengers;
  final int carbonPerKilometer;

  int get carbonFootprint => (carbonPerKilometer / passengers).round();

  bool get isTwoWheeled => this == Vehicle.bicycle;

  @override
  int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint;
}

使用枚舉

#

像任何其他靜態變數一樣存取枚舉值

dart
final favoriteColor = Color.blue;
if (favoriteColor == Color.blue) {
  print('Your favorite color is blue!');
}

枚舉中的每個值都有一個 index getter,它會傳回該值在枚舉宣告中的從零開始的位置。例如,第一個值的索引為 0,而第二個值的索引為 1。

dart
assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);

若要取得所有枚舉值的清單,請使用枚舉的 values 常數。

dart
List<Color> colors = Color.values;
assert(colors[2] == Color.blue);

您可以在switch 陳述式中使用枚舉,如果您沒有處理所有枚舉值,則會收到警告

dart
var aColor = Color.blue;

switch (aColor) {
  case Color.red:
    print('Red as roses!');
  case Color.green:
    print('Green as grass!');
  default: // Without this, you see a WARNING.
    print(aColor); // 'Color.blue'
}

如果您需要存取枚舉值的名稱,例如從 Color.blue 取得 'blue',請使用 .name 屬性

dart
print(Color.blue.name); // 'blue'

您可以像在一般物件上一樣存取枚舉值的成員

dart
print(Vehicle.car.carbonFootprint);