Dart Flutter:使非常量 属性 成为常量

Dart Flutter: make non constant property constant

我有这个对象

class Foo {
  Color color;

  Foo({this.color = Colors.red});
}

我真的需要能够更新颜色 属性 所以它不能保持不变。但我需要它在 flutter_local_notifications

期间保持不变
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 常量需要初始化为:

  • 基本类型的值
  • 仅使用基本或按位运算符派生的文字值
  • 常量构造函数

这就是为什么你需要使用 Colors.red,它是初始化 AndroidNotificationDetails 时的常量。其他选项是使用 final 关键字而不是 const,这仍然使您的 AndroidNotificationDetails 变量不可变并且在启动时不需要常量值。