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

Dart中如何打印enum枚举值的成员名,不显示枚举类前缀?

Dart 枚举值去掉前缀打印的实现方法

方法1:使用内置name属性(推荐,Dart 2.15+ 支持)

Dart 2.15版本之后为所有枚举类型新增了内置的name getter,直接返回不带前缀的枚举值字符串,是目前最优的解决方案。
修改后的代码如下:

enum Move { rock, paper, scissors }

void main() {
  var playerMove = Move.rock;
  print(playerMove.name); // 输出结果为 rock
}

方法2:拆分toString()返回值(兼容老版本Dart)

如果使用的Dart版本低于2.15,没有内置name属性,可以手动拆分枚举默认toString()返回的字符串:

enum Move { rock, paper, scissors }

void main() {
  var playerMove = Move.rock;
  print(playerMove.toString().split('.').last); // 按点拆分后取最后一段,输出结果为 rock
}

方法3:自定义扩展方法(适合频繁调用场景)

如果项目中需要多次获取枚举的纯值名称,可以给枚举扩展自定义 getter 统一处理,提升代码可读性:

enum Move { rock, paper, scissors }

extension MoveExt on Move {
  String get rawValue => toString().split('.').last;
  // Dart 2.15+ 也可以直接写 String get rawValue => name;
}

void main() {
  var playerMove = Move.rock;
  print(playerMove.rawValue); // 输出结果为 rock
}

内容的提问来源于stack exchange,提问作者user15255934

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:36:03