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

Dart枚举工厂方法无法通过类名调用,如何正常使用?

枚举工厂方法无法通过类名调用的解决方案

我在Flutter 3.16.5(Dart 3.2.3)环境下定义了如下枚举,希望通过City.fromName(city)的方式调用工厂方法,但实际只能通过City.korea.fromName(city)这种实例调用的方式使用,其他开发者却可以正常通过类名调用。

枚举代码:

enum City {
  us,
  korea,
  canada,
  other;

  factory City.fromName(String name) => switch (name) {
        'us' => City.us,
        'korea' => City.korea,
        'canada' => City.canada,
        _ => City.other,
      };
}

解决方法

  • 清理环境缓存:
    执行以下命令清理项目缓存,再重启IDE:

    1. flutter clean
    2. dart pub get
    3. 清除IDE缓存(比如Android Studio依次点击File -> Invalidate Caches... -> Invalidate and Restart)
      这种情况大概率是IDE或编译缓存导致的识别异常,清理后通常能恢复正常。
  • 改用静态方法替代工厂构造:
    如果清理缓存后仍无法解决,可以将工厂方法改为静态方法,写法更直观且兼容性更稳定:

    enum City {
      us,
      korea,
      canada,
      other;
    
      static City fromName(String name) => switch (name) {
            'us' => City.us,
            'korea' => City.korea,
            'canada' => City.canada,
            _ => City.other,
          };
    }
    

    之后即可正常通过City.fromName(city)调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:06:16