Flutter / Dart将Int转换为Enum

vfwfrxfs  于 12个月前  发布在  Flutter
关注(0)|答案(5)|浏览(231)

有没有一个简单的方法将一个整数值转换为枚举?我想从共享首选项中检索一个整数值并将其转换为枚举类型。
我的enum是:

enum ThemeColor { red, gree, blue, orange, pink, white, black };

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

final prefs = await SharedPreferences.getInstance();
ThemeColor c = ThemeColor.convert(prefs.getInt('theme_color')); // something like that
nhaq1z21

nhaq1z211#

在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);
  }
}
gijlo24d

gijlo24d2#

警告,请确保使用try/catch处理不存在的整数。

/// Shows what to do when creating an enum value from a integer value

enum ThemeColor { red, green,}

void main() {
  
  try {
    final nonExistent = ThemeColor.values[3];
    print("Non existent enum is $nonExistent");

  }
  catch(e) {
    print("Non existent enum thrown"); 
  }
}

// Non existent enum thrown

dartpad:https://dartpad.dev/?id=4e99d3f578311288842a0ab5e069797e

8dtrkrch

8dtrkrch3#

另一个具有增强枚举的解决方案,加上:

  • 附加到枚举值的更多属性
  • 工厂构造器
  • 构造函数中的回退值
  • Comparable接口的实现
  • 比较运算符过载
  • 转换为Map

在Dart 2.19.6上测试。

enum AuthLevel implements Comparable<AuthLevel> {
  guest(1, 'Guest'),
  user(2, 'Registered user'),
  admin(5, 'Administrator'),
  developer(9, 'Developer');

  final int level;
  final String desc;

  const AuthLevel(this.level, this.desc);

  // Conversion from int
  factory AuthLevel.fromInt(int level) =>
      values.firstWhere((value) => value.level == level, orElse: () => guest);

  // Conversion to int
  int get toInt => level;

  @override
  int compareTo(AuthLevel other) => level - other.level;

  // Comparison operator(s)
  bool operator >=(AuthLevel other) => level >= other.level;
  // ... possibly add more

  @override
  String toString() => '{level: $level, desc: $desc}';

  // Conversion to map
  Map<int, String> toMap() =>
      {for (var value in AuthLevel.values) value.level: value.desc};
}
92dk7w1h

92dk7w1h4#

int idx = 2;
print(ThemeColor.values[idx]);

应该给予你

ThemeColor.blue
xzabzqsa

xzabzqsa5#

您可以用途:

ThemeColor.red.index

应该给予你

0

相关问题