94

Is there a simple way to convert an integer value to enum? I want to retrieve an integer value from shared preference and convert it to an enum type.

My enum is:

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

I want to easily convert an integer to an enum:

final prefs = await SharedPreferences.getInstance();
ThemeColor c = ThemeColor.convert(prefs.getInt('theme_color')); // something like that
henrykodev
  • 2,964
  • 3
  • 27
  • 39

5 Answers5

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

should give you

ThemeColor.blue
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
31

You can use:

ThemeColor.red.index

should give you

0
Zig Razor
  • 3,381
  • 2
  • 15
  • 35
Farman Ameer
  • 1,234
  • 2
  • 16
  • 22
12

In Dart 2.17, you can use enhanced enums with values (which could have a different value to your index). Make sure you use the correct one for your needs. You can also define your own getter on your enum.

//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);
  }
}
atreeon
  • 21,799
  • 13
  • 85
  • 104
2

Warning, make sure you handle non-existent integer with a 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

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

Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95
0

Another solution with enhanced enums, plus:

  • More propertie(s) attached to enum values
  • Factory constructor
  • Fallback value in constructor
  • Implementation of the Comparable interface
  • Overload of comparison operator(s)
  • Conversion to map

Tested on 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};
}
Giorgio Barchiesi
  • 6,109
  • 3
  • 32
  • 36