toHex method

String toHex({
  1. bool includeAlpha = true,
  2. bool includeHash = true,
})

Converts this color to a hexadecimal string

includeAlpha Whether to include the alpha channel (defaults to true) includeHash Whether to include the # prefix (defaults to true)

Returns a hex string representation of the color

Example:

final color = Color(0xFFFF5722);
print(color.toHex()); // #FFFF5722
print(color.toHex(includeAlpha: false)); // #FF5722

Implementation

String toHex({bool includeAlpha = true, bool includeHash = true}) {
  final hash = includeHash ? '#' : '';
  if (includeAlpha) {
    return '$hash${((a * 255.0).round() & 0xff).toRadixString(16).padLeft(2, '0').toUpperCase()}'
        '${((r * 255.0).round() & 0xff).toRadixString(16).padLeft(2, '0').toUpperCase()}'
        '${((g * 255.0).round() & 0xff).toRadixString(16).padLeft(2, '0').toUpperCase()}'
        '${((b * 255.0).round() & 0xff).toRadixString(16).padLeft(2, '0').toUpperCase()}';
  } else {
    return '$hash${((r * 255.0).round() & 0xff).toRadixString(16).padLeft(2, '0').toUpperCase()}'
        '${((g * 255.0).round() & 0xff).toRadixString(16).padLeft(2, '0').toUpperCase()}'
        '${((b * 255.0).round() & 0xff).toRadixString(16).padLeft(2, '0').toUpperCase()}';
  }
}