Home > Software engineering >  Flutter: create const color from hex string
Flutter: create const color from hex string

Time:04-07

I am using Firebase remote config to store my color values. This gives me the flexibilty to update colors without the need to update my app. Now I have written myself a helper function which returns the color object.

In my Firebase remote config I have stored the hex color codes as strings. However, now I am facing the problem that my colors are no constants (const). This is a huge problem for me as I have set default color values in some constructors like here:

const CustomIcon(
    {required this.iconType,
    this.size,
    this.color = Helper.getColor("black"),
    Key? key})
    : super(key: key);

Because my color is not a const value anymore I get the following error: https://dart.dev/tools/diagnostic-messages#non_constant_default_value

This is my helper function:

static Color getColor(colorName) {
  final remoteConfig = FirebaseRemoteConfig.instance;

  String colorString = remoteConfig.getString(colorName);

  const color = Color(int.parse(colorString));

  return color;
}

Do you have any idea on how I can solve this problem?

Kind regards

CodePudding user response:

You sadly won't be able to const anything from the API. The const keyword implies that the Dart Analyzer knows what the value will be even before compiling. This isn't the case here, as the values come from the API.

However, you can still have a solution, by using a local Color default value, and checking for a null color.

class CustomIcon extends StatelessWidget {
  final String iconType;
  final int? size;
  final Color? color;

  late final Color defaultColor = Helper.getColor("black");

  CustomIcon({required this.iconType, this.size, this.color, Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final _color = color ?? defaultColor;
    // Build your Widget
    return Container(
      color: _color,
      height: 50,
      width: 50,
    );
  }
}

Here is a simple DartPad showing it in action: https://dartpad.dev/?id=562c943972abaefd29b7b264e16ad5aa

  • Related