Flutter:将值分配给const color时出错 [英] Flutter: Error in assigning value to const color
问题描述
const color = Colors.red; // no error
const color100 = Colors.red[100]; // error
如果 Colors.red
是一个编译时间常数,为什么 Colors.red [100]
不是.
If Colors.red
is a compile time constant, why Colors.red[100]
isn't.
推荐答案
因为您只能将常量值分配给 const
变量.
Because you can only assign constant values to a const
variable.
并且没有/不能将运算符 T1运算符[](T2 i)
的返回类型声明为 const
And the return type of an operator T1 operator [](T2 i)
isn't/can't be declared as const
所以你不能做 const a = b [c];
不/不能将函数 T1 x(T2 y)
的返回类型声明为 const
Like the return type of a function T1 x(T2 y)
isn't/can't be declared as const
所以你不能做 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.
因此,如果声明 ClassA
的构造函数为 const
So you can do const a = ClassA();
if the constructor of ClassA
is declared const
这篇关于Flutter:将值分配给const color时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!