toColor method

Color toColor()

Converts string in hex representation into a Color.

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

Example:

'#ff00ff'.toColor();  // pink
'ff0000'.toColor();   // red
'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);
    }
  } catch (error) {
    // will throw anyway
  }

  throw ArgumentError('Can not interpret string $this');
}