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

Is there any way to create Map with enum as key that ensure operator[] is not null?

enum SomeEnum { first, second }

Map<SomeEnum, String(or any type)> someMap = {
  SomeEnum.first: 'first',
  SomeEnum.second: 'second',
};

String variable = someMap[SomeEnum.first]; <- nullable

In codes above, someMap[SomeEnum.{anything}] defenitely can’t be null because it have all possible SomeEnum as key.

But this causing error because someMap[SomeEnum.first] is nullable, can’t assign to type String

How do I tell flutter that this have all possible enum values and 100% can’t be null without using ! (I don’t want to use it because I use this map a lot and this is a little bit annoying)

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

>Solution :

If that is your literal enum and map you don’t need that map. Use SomeEnum.first.name to get the string.

If the strings are different. I would use a different approach. When using Dart 2.17.0 or higher you can use enhanced enums and simple add methods to enums like this for example

enum SomeEnum { first, second;
  String getString() {
    switch (this) {
      case SomeEnum.first: return "first string";
      case SomeEnum.second: return "second string";
    }
  }

  int toInt() {
    switch (this) {
      case SomeEnum.first: return 1;
      case SomeEnum.second: return 2;
    }
  }
}

And then use Some.first.getString() wherever you need. Or Some.first.toInt() to get ints

For lower Dart versions you can write an extension instead and use it in the same way:

extension SomeEnumExtension on SomeEnum {
  String getString() {
    switch (this) {
      case SomeEnum.first: return "first string";
      case SomeEnum.second: return "second string";
    }
  }
}
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