toColor method Null safety

Color toColor()

Converts string in hex representation into a Color. Returns black (#000000) if string is not interpretable.

You can use 6-char hex color (RRGGBB), 8-char hex color (RRGGBBAA), 3-char hex color (RGB), 4-char hex color (RGBA) or a valid HTML color name. The hash (#) is optional for hex color strings.

Example:

'#ff00ff'.toColor();  // pink
'ff0000'.toColor();   // red
'ff000080'.toColor(); // red with 50% opacity
'00f'.toColor();      // blue
'red'.toColor();      // red (HTML color name)
'deeppink'.toColor(); // deep pink (HTML color name)

Implementation

Color toColor() {
  if (_isHtmlColorName(this)) {
    return _getColorByHtmlColorName(this);
  }

  try {
    var color = _removeLeadingHash(this);

    if (color.length == 6) {
      return _sixCharHexToColor(color);
    }

    if (color.length == 3) {
      return _threeCharHexToColor(color);
    }

    if (color.length == 8) {
      return _eightCharHexToColor(color);
    }

    if (color.length == 4) {
      return _fourCharHexToColor(color);
    }
  } catch (error) {
    // will throw anyway
  }

  return Color.fromARGB(255, 0, 0, 0);
}