如何解决Dart Flutter:使非常量属性保持不变
我有这个对象
class Foo {
Color color;
Foo({this.color = Colors.red});
}
我真的需要能够更新颜色属性,所以它不能是恒定的。但是我需要它对于 flutter_local_notifications 保持不变
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('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
变量不可变,并且在启动时不需要常量值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。