-2
    const kBorderStyle2 = BoxDecoration(
  borderRadius: BorderRadius.all(
    Radius.circular(20),
  ),
  border: Border.all(color: Colors.greenAccent,),
);

Hi, I've been learning flutter on my own and got stuck on this error. I have a constants.dart file where I am saving all the styles for the app. Whenever I try to add the color: Colors.greenAccent, to the const, I get an error "const variable must be initialized with a constant value." but then I change const to var and the problem goes away.

I also get the same error for the following code:

const kBorderStyleX = BoxDecoration(
  color: Colors.greenAccent,
  borderRadius: BorderRadius.circular(20),
);

This goes away when I change it to:

const kBorderStyle1 = BoxDecoration(
  color: Colors.greenAccent,
  borderRadius: BorderRadius.all(
    Radius.circular(20),
  ),
);

Is there something I am missing with const? Any reason why I am getting the error?

Ashwini
  • 15
  • 6
  • 1
    As far as your confusion regarding `const Colors.greenAccent` is considered. Then the constructor from `Flutter` comes with `const` itself. Refer to the link below you will get some more information: https://stackoverflow.com/questions/47996420/what-color-system-does-flutter-use-and-why-do-we-use-const-color-instead-of-n – Hamza Oct 21 '20 at 12:58

1 Answers1

2

To check whether an object is eligible to be assigned to a const variable, Dart relies on the constructor that created the object, which can be marked as const or not (e.g. const BorderRadius.all() vs. BorderRadius.circular()).

This is why even though an object may even not be able to be changed, Dart can treat it as it could, if the used constructor is not marked as const.

Raoul Müller
  • 397
  • 2
  • 9