Flutter / Dart Convert Int to Enum

我是研究僧i 提交于 2020-12-02 00:03:49

问题


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

回答1:


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

should give you

ThemeColor.blue



回答2:


You can use:

ThemeColor.red.index

should give you

0


来源:https://stackoverflow.com/questions/51190035/flutter-dart-convert-int-to-enum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!