Flutter Dart Enum 增强新特性

24 min read

Dart还允许枚举声明使用字段、方法和常量构造函数声明类,这些构造函数限制为固定数量的已知常量实例。

要声明增强的枚举,请遵循类似于普通类的语法,但有一些额外要求:

  • 实例变量必须是final,包括由mixin添加的变量。
  • 所有生成构造函数都必须是常量。
  • 工厂构造函数只能返回一个固定的已知枚举实例。
  • 由于枚举是自动扩展的,因此无法扩展其他类。
  • 索引、哈希代码、相等运算符==不能有重写。
  • 不能在枚举中声明名为values的成员,因为它会与自动生成的静态值getter冲突。
  • 必须在声明的开头声明枚举的所有实例,并且必须至少声明一个实例。

下面是一个示例,它声明了一个具有多个实例、实例变量、getter和实现接口的增强枚举:

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();

  @override
  int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint;
}
enum Status{
    ToBeSent(value: 0, label: "待发送", color: Color(0xffb4b4b4)),
    HasBeenSent(value: 1, label: "已发送", color: Color(0xfff79d8c)),
    Received(value: 2, label: "已接收", color: Color(0xff00b9f1)),
    Replied(value: 3, label: "已回复", color: Color(0xff2699f6)),
    Canceled(value: -1, label: "已取消", color: Color(0xff75d239));
    
    final int value;
    final String label;
    final Color color;

  const Status({
    required this.value,
    required this.label,
    required this.color,
  });
  
  
  /// 解析从后台传来的值
  static Status parse(int i) {
    if (i == -1) return Status.Canceled;
    return Status.values[i];
  }    
}

类似于Swift 的 Struct

import 'package:flutter/material.dart';

/// Categorization of one file.
/// We use this information for a better UX.
enum FileType {
  image(Icons.image),
  video(Icons.movie),
  pdf(Icons.description),
  text(Icons.subject),
  other(Icons.file_present_sharp);

  const FileType(this.icon);

  final IconData icon;
}