Search code examples
flutterclassstaticconstants

Flutter Grouping Static Classes removes constant from field, why?


When creating a class for static Color resources in flutter and grouping these into sub classes, implementation of the asset later causes an error stating that the static const resource is not a constant value even though it is declared as a static const and the sub class has only final fields. What is going on?

The following code groups static resources.

class AppColor {
static const _Label label = _Label();

}

class _Label {
  const _Label();
  final Color primary = const Color.fromRGBO(0, 0, 0, 1);
  final Color secondary = const Color.fromRGBO(46, 52, 58, 0.84);
}

However when using this resource in a Widget constructor it shows the error:

class AWidget extends StatelessWidget {
  AWidget({
    super.key,
    Color color = AppColor.label.primary, 
    //!!!  The default value of an optional parameter must be constant
  });
  final Color color;
}

Why? It is constant is it not? This problem only occurs when grouping the static resources. If I list them all in AppColor then this does not happen but its not friendly to do that with the amount of resources I have.


Solution

  • In constructors, you can only use variables initialized with const as an optional parameter value, which means that they must be known at compile time.

    You are getting this error because primary field in Label class is intitialized with final not const.