dart 位移位枚举值作为常量

vmjh9lq9  于 2023-06-19  发布在  其他
关注(0)|答案(2)|浏览(164)

为什么逐位枚举索引值不允许用作Dart中的常量?即:

enum Foo {
  item1,
  item2,
}

enum Bar {
  item1,
  item2,
}

const fooBar = Foo.item1.index | Bar.item2.index;

谢谢你
乔恩

esbemjvw

esbemjvw1#

如果从dart:core查看Enum类,您会发现index是一个getter,它不是编译时常量;因此,您不能将其分配给const变量。
https://api.dart.dev/stable/2.17.1/dart-core/Enum/index.html
显然,在Dart中支持按位枚举存在开放问题。参见#33698(其中一个回复中提供了一个解决方法类)和#158

xfb7svmp

xfb7svmp2#

这是我在Dart/Flutter中枚举BitFlags的解决方案

// 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

相关问题