Flutter: Error in assigning value to const color

帅比萌擦擦* 提交于 2021-02-18 17:55:28

问题


const color = Colors.red; // no error
const color100 = Colors.red[100]; // error

If Colors.red is a compile time constant, why Colors.red[100] isn't.


回答1:


Because you can only assign constant values to a const variable.

And the return type of an operator T1 operator [](T2 i) isn't/can't be declared as const

So you can't do const a = b[c];

Like the return type of a function T1 x(T2 y) isn't/can't be declared as const

So you can't do const z = x(y);

Because when you use an operator or a function, you are not creating the return value at the moment of the call, so you are not returning a constant value. That can only be achieved with a constructor.

So you can do const a = ClassA(); if the constructor of ClassA is declared const




回答2:


Edit Also map is getting same error

Looks like its about dart, because when i tried run this code, it is gave me same error

const x = const ['value'];
const y = x[0]; // error
const z = x; // no error



回答3:


You can assign the value of Colors.red to a const variable because Colors.red is a static const instance of MaterialColor. MaterialColor extends ColorSwatch which in turn extends Color, which is why you can use a MaterialColor as a Color.

Colors.red[100] cannot be assigned to a const variable because its value is obtained by applying the [] operator defined within ColorSwatch:

Color operator [](T index) => _swatch[index];

Operators are similar to named functions - the main difference is they use a different syntax. Operators and functions cannot use the const keyword as of now even if they only return const values, and as such their return values cannot be assigned to const variables either.



来源:https://stackoverflow.com/questions/58520593/flutter-error-in-assigning-value-to-const-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!