A Map with the compile-time check that every enum
constant has an entry in it.
Overview
For an enum
like this
enum Fruit { apple, orange, banana }
... you can generate the following class:
class FruitMap<V> extends EnumMap<Fruit, V> { // implements Map<Fruit, V>
FruitMap({
required this.apple,
required this.orange,
required this.banana,
});
// ...
}
Which means that the app will only build if you set all the values in the constructor. And then you can treat this object like an ordinary map.
Usage
@MakeMap()
@MakeUnmodifiableMap()
enum Fruit { apple, orange, banana }
void main() {
final modifiableMap = FruitMap<String>(apple: 'a', orange: 'o', banana: 'b');
print(modifiableMap); // prints: {Fruit.apple: a, Fruit.orange: o, Fruit.banana: b}
print(modifiableMap[Fruit.apple]); // prints: a
print(modifiableMap.get(Fruit.apple)); // prints: a
const unmodifiableMap = UnmodifiableFruitMap<String>(apple: 'a', orange: 'o', banana: 'b');
print(unmodifiableMap); // prints: {Fruit.apple: a, Fruit.orange: o, Fruit.banana: b}
print(unmodifiableMap[Fruit.apple]); // prints: a
print(unmodifiableMap.get(Fruit.apple)); // prints: a
}
The generated classes contain:
- All 21 of the public members of the
Map
interface. V get(Fruit key)
-- the non-nullable getter that guarantees the result of typeV
.toString()
that works like with the default maps.
Migrating from the Pre-Macro Version
- Change the annotations:
- Replace
@enumMap
with@MakeMap()
. - Replace
@unmodifiableEnumMap
with@MakeUnmodifiableMap()
.
- Replace
- Delete all
*.g.dart
files. - Delete
enum_map_gen
package from yourpubspec.yaml
. Rundart pub get
. - Check if you still need
build_runner
package for other packages. If you don't, delete it and rundart pub get
. - Otherwise, regenerate all
*.g.dart
files that exist for reasons other than this package.
Support Chat
Do you have any questions? Feel free to ask in the Telegram Support Chat.
Or even just join to say 'Hi!'. I like to hear from the users.