Flutter Dart 枚举类从任意数字开始

18 min read
import 'package:flutter/material.dart';

enum Status {
  /// 待发送
  ToBeSent,

  /// 已发送
  HasBeenSent,

  /// 已接收
  Received,

  /// 已回复
  Replied,

  /// 已取消
  Canceled,
}

extension StatusExtension on Status {
  static const List<int> values = [0, 1, 2, 3, -1];
  static const List<String> labels = ["待发送", "已发送", "已接收", "已回复", "已取消"];
  static const List<Color> colors = [
    Color(0xffb4b4b4),
    Color(0xfff79d8c),
    Color(0xff00b9f1),
    Color(0xff2699f6),
    Color(0xff75d239),
  ];

  /// 真正后台想要的值
  int get value => values[index];

  /// 展示文字
  String get label => labels[index];

  /// 展示颜色
  Color get color => colors[index];

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

void main() {
  print(Status.ToBeSent.label);
	print(Status.parse(-1));
}