Flutter/Dart将Int转换为Enum

hen*_*000 13 enums dart flutter

有一种简单的方法可以将整数值转换为枚举吗?我想从共享首选项中检索一个整数值并将其转换为枚举类型.

我的枚举是:

enum ThemeColor { red, gree, blue, orange, pink, white, black };
Run Code Online (Sandbox Code Playgroud)

我想轻松地将整数转换为枚举:

final prefs = await SharedPreferences.getInstance();
ThemeColor c = ThemeColor.convert(prefs.getInt('theme_color')); // something like that
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 25

int idx = 2;
print(ThemeColor.values[idx]);
Run Code Online (Sandbox Code Playgroud)

应该给你

ThemeColor.blue
Run Code Online (Sandbox Code Playgroud)

  • 哦,太明显了……在发布问题之前,应该进行更多研究。 (2认同)

atr*_*eon 14

在 Dart 2.17 中,您可以使用带有值的增强枚举(可能与索引具有不同的值)。确保您使用适合您需求的正确产品。您还可以在枚举上定义自己的 getter。

//returns Foo.one
print(Foo.values.firstWhere((x) => x.value == 1));
  
//returns Foo.two
print(Foo.values[1]);
  
//returns Foo.one
print(Foo.getByValue(1));

enum Foo {
  one(1),
  two(2);

  const Foo(this.value);
  final num value;
  
  static Foo getByValue(num i){
    return Foo.values.firstWhere((x) => x.value == i);
  }
}
Run Code Online (Sandbox Code Playgroud)