有没有一个简单的方法将一个整数值转换为枚举?我想从共享首选项中检索一个整数值并将其转换为枚举类型。
我的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
5条答案
按热度按时间nhaq1z211#
在Dart 2.17中,您可以使用带值的增强枚举(它可能与索引具有不同的值)。请确保您使用正确的一个为您的需要。你也可以在你的枚举上定义你自己的getter。
gijlo24d2#
警告,请确保使用try/catch处理不存在的整数。
dartpad:https://dartpad.dev/?id=4e99d3f578311288842a0ab5e069797e
8dtrkrch3#
另一个具有增强枚举的解决方案,加上:
在Dart 2.19.6上测试。
92dk7w1h4#
应该给予你
xzabzqsa5#
您可以用途:
应该给予你