// Mixin to create Enum for bitflags uses.
mixin BzpFlagsEnum on Enum {
// value receive a bitwise shift operation. It means "shift the bits of 1 to the left by index places". So, "1,10,100,1000..." == 1,2,4,8,16....
int get value => 1 << index;
// Creates a operator "|" for enum.
int operator |(other) => value | other.value;
}
// Extension "int" to verify that value contains the enum flag.
extension ExtensionFlag on int {
bool has(BzpFlagsEnum enumFlag) => this & enumFlag.value == enumFlag.value;
}
// A sample.
enum FormActions with BzpFlagsEnum {
noAction,
editingData,
structureFields,
all;
}
int _sanabio = FormActions.editingData | FormActions.structureFields; // 6 ( 2 | 4)
_sanabio.has(FormActions.noAction); // false
_sanabio.has(FormActions.editingData); // true
_sanabio.has(FormActions.all); // false
_sanabio.has(FormActions.structureFields); // true
2条答案
按热度按时间esbemjvw1#
如果从
dart:core
查看Enum
类,您会发现index
是一个getter,它不是编译时常量;因此,您不能将其分配给const
变量。https://api.dart.dev/stable/2.17.1/dart-core/Enum/index.html
显然,在Dart中支持按位枚举存在开放问题。参见#33698(其中一个回复中提供了一个解决方法类)和#158。
xfb7svmp2#
这是我在Dart/Flutter中枚举BitFlags的解决方案