You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dart中为enum枚举实现类似Swift的raw value赋值功能?

Dart实现枚举自定义原生值的方案

Dart支持两种常用方式实现类似Swift的枚举原生值绑定效果,具体实现如下:

方案1:使用Dart 2.17+ 增强枚举(官方推荐)

Dart 2.17版本新增的增强枚举特性,直接支持给枚举值绑定自定义参数,和Swift的枚举原生值用法高度一致:

enum Game {
  // 给每个枚举值绑定自定义的int类型原生值
  lol(1),
  dnf(2),
  dota(3);

  // 定义存储原生值的属性,支持任意类型,不限于int
  final int rawValue;
  // 声明const构造方法
  const Game(this.rawValue);

  // 可选扩展:实现通过原生值反向获取枚举实例的方法
  static Game? fromRawValue(int raw) {
    try {
      return Game.values.firstWhere((element) => element.rawValue == raw);
    } catch(e) {
      return null;
    }
  }
}

使用示例:

  • 获取枚举原生值:print(Game.dnf.rawValue); // 输出2
  • 原生值转枚举:final game = Game.fromRawValue(3); // 得到Game.dota

小提示:Dart原生枚举默认自带index属性,取值为从0开始的序号,如Game.lol.index默认值为0,如果你不需要自定义数值,可以直接使用该属性,无需额外扩展。

方案2:低版本Dart兼容方案(扩展属性实现)

如果你的项目Dart版本低于2.17,无法使用增强枚举,可以通过extension扩展给基础枚举绑定自定义值:
首先定义基础枚举:

enum Game {
  lol,
  dnf,
  dota,
}

给枚举添加扩展:

extension GameRawValue on Game {
  // 绑定自定义原生值
  int get rawValue {
    switch(this) {
      case Game.lol: return 1;
      case Game.dnf: return 2;
      case Game.dota: return 3;
    }
  }

  // 可选:原生值反向转枚举方法
  static Game? fromRawValue(int raw) {
    switch(raw) {
      case 1: return Game.lol;
      case 2: return Game.dnf;
      case 3: return Game.dota;
      default: return null;
    }
  }
}

该方案的使用方式和增强枚举完全一致,直接调用rawValue属性即可。


内容的提问来源于stack exchange,提问作者无夜之星辰

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:06:01