How can I require the Dart compiler to warn me when I forget to include all members of an enum in a map? For example, in the following:
enum Size {
small,
medium,
large,
}
// This is a valid Dart code. Dart compiler doesn't require `Size.large` to be present.
final Map<Size, ButtonSize> sizeMap = {
Size.small: const MyClass(),
Size.medium: const MyClass(),
};
The Dart compiler isn't that restrictive. It doesn't require all enum values to be present in the Map, so I can't be sure that the following code will return an instance of MyClass. It might resolve to null:
final MyClass instance = sizeMap[Size.small]; // unsafe
I have to either do this:
final MyClass? instance = sizeMap[Size.small]; // `instance` might be `null`
or this:
final MyClass instance = sizeMap[Size.small] as MyClass; // `instance` might still be `null`, but we're pretending it's not.
Both solutions are far from perfect. The first one implies further null checks in the code, the second one smells because of typecasting.
Is there any way to declare the type of sizeMap so that all enum values must be present?