Flutter 在dart中,如何将常量映射中的值赋给常量变量?

Flutter 在dart中,如何将常量映射中的值赋给常量变量?,flutter,dart,Flutter,Dart,假设我有一个ColorPalette类,如下所示: class ColorPalette { static const Map<int, Color> gray = { 400: Color(0xFFDDDDDD), 500: Color(0xFFEEEEEE), // ... }; // Primary colors in separate variable static const Color primaryBlue = Color(0x

假设我有一个ColorPalette类,如下所示:

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);
  // ...
}
另外,在分配贴图时,执行
500:const Color(…)
static const map gray=const{…}
也不起作用

所以我怀疑这是抛出错误,可能是因为编译器在编译时不计算映射中的所有条目,因此,使用给定键访问的值只能在运行时知道


是否存在将映射中的值指定给需要常量值的变量的变通方法?

没有变通方法

e1[e2]
形式的表达式不能是常量。
[]
运算符是一种方法(所有用户可定义的运算符都是),除了已知系统类型上的极少量操作外,您不能在编译时调用方法。映射查找,即使是在常量映射上,也不是例外


之所以
colorplate.primaryBlue
有效,是因为它直接引用
const
变量。

您不能。你的要求不被支持。好的,现在清楚了。我想重构ColorPalette类是个更好的主意,因为在很多情况下,映射中的值必须被指定为构造函数中另一个类中成员的默认值。谢谢你的解释!谢谢Stackoverflow的“类似问题”框,我正要问同样的问题!操作员
[]
是一种方法,我理解,它感觉应该有一种方法来解决这个问题……如果不是现在,那么在将来……但我不知道@Irn!
class SomeOtherClass {
  static const Map<String, Color> stateColor = {
    // Error
    'pressed': ColorPalette.gray[500],
  }
}
...
    'pressed': ColorPalette.primaryBlue,
...