I have this 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

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

So how can I make Foo.color constant?

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


Solution 1: Bach

By definition, Dart constant needs to be initialized with:

  • 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. 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.