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:flutter cleandart pub get- 清除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
相关产品推荐
相关产品推荐

