Enums in Dart are worth an extension
Enums in Dart are worth an extension
Note! Time has moved on and in the meantime Dart has capabilities that make this post obsolete. You can read about the new features here
Dart is a relatively simple programming language.
In general this is a good thing as the number of possibilities and patterns you have to know in order to develop something with it or when reading code is lower.
On the other hand you will miss certain features that other programming languages have that can lead to quite elegant solutions for certain problems.
Enums int Dart are such a case.
Enums are very simple in Dart. In general, they are classes / objects like everything else, but you can’t do neat tricks with them like for example with C#.
Let’s assume we have a byte value and want to read some bits of it. Those bits should have names (mapped to an enum) for better understandability.
Enums in C#
In C# there is a language feature for exactly that. You can use any enum to represent bits in a bit field.
[Flags]
public enum FlagValues : byte
{
None = 0x00,
Flag1 = 0x01 << 0,
Flag2 = 0x01 << 1,
Flag3 = 0x01 << 2,
Flag4 = 0x01 << 3,
Option4 = 0x01 << 4,
All = 0xFF
};
// later in the code
byte val = 0x05; //00000101
var flags = (FlagValues) val;
flags.HasFlag(FlagValues.Flag1); // true
flags.HasFlag(FlagValues.Flag2); // false
flags.HasFlag(FlagValues.Flag3); // true
flags.HasFlag(FlagValues.Flag4); // false
You can even do bitwise operations directly with the enum like
Read more...