toColor static method

Color? toColor(
  1. String? color
)

Implementation

static Color? toColor(String? color) {
  try {
    if (isNullOrEmpty(color)) return null;

    color = color!.toLowerCase().trim();

    // color code
    if (colors.containsKey(color)) return colors[color.toLowerCase()];

    // random color
    if (color == 'random') {
      return colors[colors.keys.elementAt(Random().nextInt(colors.length))];
    }

    // # hex color w/out alpha
    if (color.startsWith('#') && color.length == 7) {
      var clr = color.substring(1);
      return Color(int.parse(clr, radix: 16) + 0xFF000000);
    }

    // # hex color w/ alpha
    if (color.startsWith('#') && color.length == 9) {
      var clr = '${color.substring(7, 9)}${color.substring(1, 7)}';
      return Color(int.parse(clr, radix: 16) + 0x00000000);
    }

    // 0x hex color w/out alpha
    if (color.startsWith('0x') && color.length == 8) {
      var clr = color.substring(2);
      return Color(int.parse(clr, radix: 16) + 0xFF000000);
    }

    // 0x hex color w/ alpha
    if (color.startsWith('0x') && color.length == 10) {
      var clr = '${color.substring(8, 10)}${color.substring(2, 8)}';
      return Color(int.parse(clr, radix: 16) + 0x00000000);
    }
  }

  // ignore: empty_catches
  catch (e) {}
  return null;
}