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

如何在Dart中列出所有sealed类的子类型?

在Dart中获取Sealed类的所有子类型(类似Enum.values)

Dart的sealed类本身没有内置的子类型列表API,但可以通过在sealed类中手动定义静态列表的方式实现需求,完全不需要镜像或额外枚举关联,具体实现如下:

实现方案

直接在sealed类中添加静态属性,包含所有子类型的实例或类型本身,可根据使用场景选择:

场景1:遍历子类型的实例

如果需要像枚举那样遍历实例对象:

sealed class Foo {}
class Bar extends Foo {}
class Baz extends Foo {}

extension FooSubtypes on Foo {
  static final List<Foo> subtypes = [Bar(), Baz()];
}

void main() {
  for (final subtype in FooSubtypes.subtypes) {
    switch (subtype) {
      case Bar():
        print('Bar instance');
      case Baz():
        print('Baz instance');
    }
  }
}

场景2:遍历子类型的类型对象

如果需要操作类型本身(比如创建实例、获取类型名):

sealed class Foo {}
class Bar extends Foo {}
class Baz extends Foo {}

extension FooSubtypes on Foo {
  static final List<Type> subtypeTypes = [Bar, Baz];
}

void main() {
  for (final type in FooSubtypes.subtypeTypes) {
    print(type.toString());
    // 如需创建实例,可结合工厂构造或其他方式实现
  }
}

注意事项

  • Dart的sealed类要求所有子类型必须和父类在同一个库中,因此手动维护静态列表是安全的,不会出现外部新增子类型遗漏的情况
  • 每次新增子类型时,同步更新静态列表即可,这是唯一的额外维护成本,但相比镜像方案更高效且类型安全

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:42:43