Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

specify variable as some kind of enum in dart

Here’s a little fun class:

abstract class Concept {
  late Enum option;
  String get name => option.name;
}

and you might implement it like this:

enum FeeOption {
  fast,
  standard,
  slow,
}
class FastFeeRate extends Concept {
  FeeOption option = FeeOption.fast;
}
print(FastFeeRate().name); // 'fast'

but then you get an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

FastFeeRate.option=' ('void Function(FeeOption)') isn't a valid override of 'Concept.option=' ('void Function(Enum)').

So, how do you specify a variable as any kind of enum, not Enum itself?

>Solution :

Your class Concept has a mutable (late, but that doesn’t matter) field with type Enum. That means it has a setter named option= with an argument type of Enum.

The subclass FastFeeRate is a subclass. It has another field (your class has two fields!) also named option, which has a setter with an argument type of FastFeeRate.

That’s not a valid override. The subclass setter must accept all arguments that the superclass setter does, but it doesn’t accept all Enum values.

What you might have intended to do is:

abstract class Concept<T extends Enum> {
  T option;
  Concept(this.option);
  String get name => option.name;
}
class FastFeeRate extends Concept<FeeOption> {
  FastFeeRate() : super(FeeOption.fast);
}

or

abstract class Concept<T extends Enum> {
  abstract T option;
  String get name => option.name;
}
class FastFeeRate extends Concept<FeeOption> {
  FastFeeRate option = FeeOption.fast;
}

depending on whether you want to define the field in the superclass or the subclass (but make sure to only define a concrete field in one of them).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading