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

Dart中如何实现类似Swift枚举关联值,从枚举case返回不同类型实例

Dart等效实现方案

Dart 3.0及以上版本已经原生支持Swift风格的带关联值枚举,搭配模式匹配可以完全实现你要的效果,和Swift的实现逻辑几乎一致,具体代码如下:


1. 定义规则数据类

和Swift的struct对应,Dart中直接定义不可变类即可:

// 此处补全示例依赖的LampColor枚举,可根据你的业务调整
enum LampColor { red, green, blue }

final class LampRule {
  final LampColor ruleTriggerColor;
  final int ruleSustainedMilliseconds;

  const LampRule({
    required this.ruleTriggerColor,
    required this.ruleSustainedMilliseconds,
  });
}

final class CounterRule {
  final int ruleLimit;

  const CounterRule({required this.ruleLimit});
}

2. 定义带关联值的枚举

和Swift的枚举关联值写法对应,Dart的枚举支持为不同case绑定不同类型的关联值:

enum SensorTypeRule {
  // 每个case对应一个关联类型的构造器
  lamp(LampRule rule),
  counter(CounterRule rule);

  // 枚举关联值的通用存储字段
  final Object? _rule;

  // 枚举主构造器
  const SensorTypeRule(this._rule);
}

3. 调用方式(和Swift逻辑完全对齐)

通过模式匹配直接解包对应类型的rule,不需要手动做类型转换,编译期会自动校验覆盖所有case:

void main() {
  // 示例构造枚举实例
  final SensorTypeRule sensorTypeRule = SensorTypeRule.lamp(
    LampRule(
      ruleTriggerColor: LampColor.red,
      ruleSustainedMilliseconds: 2000,
    ),
  );

  // switch匹配取值,和Swift用法一致
  switch (sensorTypeRule) {
    case SensorTypeRule.lamp(rule: final rule):
      print(rule.ruleSustainedMilliseconds); // 输出2000
    case SensorTypeRule.counter(rule: final rule):
      print(rule.ruleLimit);
  }
}

如果需要简化写法,也可以用Dart的switch表达式直接赋值:

final ruleValue = switch (sensorTypeRule) {
  SensorTypeRule.lamp(rule: final rule) => rule.ruleSustainedMilliseconds,
  SensorTypeRule.counter(rule: final rule) => rule.ruleLimit,
};

低版本兼容说明

如果你使用的是Dart 3.0以下版本(对应Flutter 3.10以下),可以通过第三方代码生成库freezed实现等价的联合类型效果,当前Flutter稳定版已默认绑定Dart 3.0+,优先推荐使用原生方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:45:04