tryParseColor method

  1. @preferInline
Color? tryParseColor({
  1. String key = FlutterPropertyKeys.color,
  2. Color? defaultValue,
  3. Object? target,
  4. bool warmUp = false,
})

Retrieves a color value from the JSON map associated with the given key.

If the value associated with the key is already a Color, it returns that color. If the value is a String, it attempts to parse it into a Color. If the value is a List, it attempts to parse it into a Color. Otherwise, it returns defaultValue.

Unlike parseColor, this method does not store the parsed or existing Color back into the JSON map.

Returns:

  • A Color if the value is valid or can be parsed.
  • defaultValue if the value is not a valid Color or cannot be parsed.

Implementation

@preferInline
Color? tryParseColor({
  String key = FlutterPropertyKeys.color,
  Color? defaultValue,
  Object? target,
  bool warmUp = false,
}) {
  final value = _readProp(key, target, warmUp);

  if (value is Color) return value;

  if (value == null) return defaultValue;

  switch (value) {
    case String():
      if (envAttributeWarmUpEnabled) {
        if (warmUp) {
          return _colorFromHexString(value);
        } else {
          return _json[key] = _colorFromHexString(value);
        }
      } else {
        return _json[key] = _colorFromHexString(value);
      }
    case List():
      if (envAttributeWarmUpEnabled) {
        if (warmUp) {
          return _colorFromList(value);
        } else {
          return _json[key] = _colorFromList(value);
        }
      } else {
        return _json[key] = _colorFromList(value);
      }
    default:
      return defaultValue;
  }
}