Flutter 省道颤振:使非常量属性为常量
我有这个东西Flutter 省道颤振:使非常量属性为常量,flutter,dart,properties,constants,Flutter,Dart,Properties,Constants,我有这个东西 class Foo { Color color; Foo({this.color = Colors.red}); } 我真的需要能够更新颜色属性,所以它不能是常数。但我需要它对颤振通知保持不变 const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails('foo', 'foo', 'foo',
class Foo {
Color color;
Foo({this.color = Colors.red});
}
我真的需要能够更新颜色属性,所以它不能是常数。但我需要它对颤振通知保持不变
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('foo',
'foo', 'foo',
color: Foo.color, // this has to be constant
);
那么,如何使Foo.color
恒定
const Color color = const Foo.color; // throws error
根据定义,Dart常量需要初始化为:
- 基本类型的值
- 仅使用基本运算符或按位运算符导出的文字值
- 常量构造函数
这就是为什么需要使用
颜色.red
,这是初始化AndroidNotificationDetails
时的常量。其他选项是使用final
关键字而不是const
,这仍然使您的AndroidNotificationDetails
变量不可变,并且在启动时不需要常量值。我建议您直接使用Color valueColors.red
而不是使用Foo.Color
。