toHex method

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

Returns the hex string representation of this color.

Colors.red.toHex() // '#FF0000'
Colors.red.toHex(includeAlpha: true) // '#FFFF0000'

Implementation

String toHex({bool includeAlpha = false, bool upperCase = true}) {
  final rInt = (this.r * 255.0).round().clamp(0, 255);
  final gInt = (this.g * 255.0).round().clamp(0, 255);
  final bInt = (this.b * 255.0).round().clamp(0, 255);
  final aInt = (this.a * 255.0).round().clamp(0, 255);
  final r = rInt.toRadixString(16).padLeft(2, '0');
  final g = gInt.toRadixString(16).padLeft(2, '0');
  final b = bInt.toRadixString(16).padLeft(2, '0');
  final a = aInt.toRadixString(16).padLeft(2, '0');
  final hex = includeAlpha ? '#$a$r$g$b' : '#$r$g$b';
  return upperCase ? hex.toUpperCase() : hex.toLowerCase();
}