2

Let's say I have a ColorPalette class that looks like the following:

class ColorPalette {
  static const Map<int, Color> gray = {
    400: Color(0xFFDDDDDD),
    500: Color(0xFFEEEEEE),
    // ...
  };

  // Primary colors in separate variable
  static const Color primaryBlue = Color(0xFF0000FF);
  // ...
}

And if I were to assign a color value of the map to a variable that expects a const value:

class SomeOtherClass {
  static const Map<String, Color> stateColor = {
    // Error
    'pressed': ColorPalette.gray[500],
  }
}

Complains that "Const variables must be initialized with a constant value."

But this works fine:

...
    'pressed': ColorPalette.primaryBlue,
...

Plus when assigning map, doing 500: const Color(...) or static const Map<int, Color> gray = const {...} didn't work either.

So I suspect that this is throwing error probably because compiler doesn't evaluate all entries in the map during compile time and therefore, the value being accessed with the given key can be only known during runtime?

Is there any workaround to assign value from a map to a variable that expects a const value?

Dangular
  • 389
  • 1
  • 3
  • 15

1 Answers1

2

There is no workaround.

An expression of the form e1[e2] cannot be a constant. The [] operator is a method (all user-definable operators are), and you cannot call a method at compile time except for a very small number of operations on known system types. Map lookup, even on constant maps, is not one of those exceptions.

The reason ColorPalette.primaryBlue works is that it directly references a const variable.

lrn
  • 64,680
  • 7
  • 105
  • 121
  • Ok, it's clear now. I guess it's better idea to refactor ColorPalette class since there're also number of cases where value in the map has to be assigned as a default value of a member in another class from the constructor. Thanks for the clear explanation! – Dangular Jul 01 '20 at 03:28
  • Thank you Stackoverflow's 'similar questions box, I was just about to ask this same question! The operator `[]` is a method, I understand, it sill feels like there should be a way to get round this...if not now then in the future...but I don't know as much as @Irn ! – atreeon Jul 06 '20 at 16:42