Laurent
Laurent

Reputation: 701

How in dart, expose globaly an enum?

enum Category{ restaurant, pizzera, fast_food, other }

class XXX ...

How to acess XXX.Category statically from other classes?

Many thanks for your time ;-)

Upvotes: 6

Views: 4441

Answers (1)

Abion47
Abion47

Reputation: 24691

There's no way to expose a file, class, enum, or otherwise to the global Dart context in such a way that all other files will automatically have access to it. You can create it as a global resource and then explicitly import it in other files that need it.

(myEnum.dart)

enum MyEnum {
  value1,
  value2,
  value3,
}

(main.dart)

import 'relative/path/to/file/myEnum.dart'; // Load the contents of myEnum.dart into this file's scope

void main() {
  var e = MyEnum.value1;
  // Do whatever else you want with MyEnum
}

After rereading the question, it appears as though what you actually want is to declare the enum as a member of a static class, i.e. so you could refer to it using the syntax ClassName.EnumName.value. Sadly, nesting types is not supported in Dart. (You can't declare a class or enum within another class.)

You could use a workaround which would give the same syntactic result, though I would like to go on record as saying this is not recommended and is definitely in the territory of making things more complicated than they need to be.

(foo.dart)

enum _MyEnum {
  value1,
  value2,
  value3,
  value4,
}

class _MyEnumContainer {
  _MyEnum get value1 => _MyEnum.value1;
  _MyEnum get value2 => _MyEnum.value2;
  _MyEnum get value3 => _MyEnum.value3;
  _MyEnum get value4 => _MyEnum.value4;
}

class Foo {
  static _myEnumContainerInstance = _MyEnumContainer();
  static _MyEnumContainer get MyEnum => _myEnumContainerInstance;
}

(main.dart)

import 'foo.dart';

void main() {
  var e = Foo.MyEnum.value1;
}

Alternatively (and more recommended), you could also just import the file from the first example with a label. Granted this would purely be a cosmetic option and there would be no way to enforce this, but syntactically it achieves what you want.

import 'myEnum.dart' as Foo;

void main() {
  var e = Foo.MyEnum.value1;
}

Upvotes: 7

Related Questions