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

Time:05-20

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)

CodePudding user response:

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";
    }
  }
}
  • Related