Dangular
Dangular

Reputation: 449

In dart, how to assign a value from a const Map to a const variable?

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?

Upvotes: 2

Views: 2209

Answers (1)

lrn
lrn

Reputation: 71723

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.

Upvotes: 2

Related Questions