简体   繁体   English

Dart Flutter:使非常数属性常数

[英]Dart Flutter: make non constant property constant

I have this object我有这个 object

class Foo {
  Color color;

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

I really need to be able to update the color property so it can't be constant.我真的需要能够更新颜色属性,所以它不能保持不变。 But I need it to be constant for flutter_local_notifications但我需要它对于 flutter_local_notifications 保持不变

const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails('foo',
            'foo', 'foo',
            color: Foo.color, // this has to be constant
        );

So how can I make Foo.color constant?那么我怎样才能让Foo.color保持不变呢?

const Color color = const Foo.color; // throws error

By definition, Dart constant needs to be initialized with:根据定义,Dart 常量需要初始化为:

  • A value of a primitive type原始类型的值
  • A literal value derived by using only basic or bitwise operators仅使用基本或按位运算符派生的文字值
  • A constant constructor常量构造函数

This is why you need to use the Colors.red , which is a constant when initializing the AndroidNotificationDetails .这就是为什么您需要使用Colors.red ,它是初始化AndroidNotificationDetails时的常量。 Other options is to use the final keyword instead of const , which still make your AndroidNotificationDetails variable immutable and doesn't require a constant value when initiating.其他选项是使用final关键字而不是const ,这仍然使您的AndroidNotificationDetails变量不可变,并且在启动时不需要常量值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM