Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ColorToHex(Color).tostring() dont returns the hex code #20

Open
visign3d opened this issue Jan 14, 2024 · 2 comments
Open

ColorToHex(Color).tostring() dont returns the hex code #20

visign3d opened this issue Jan 14, 2024 · 2 comments

Comments

@visign3d
Copy link

var string hexcode = ColorToHex(HexColor('#460000')).toString();
Expected: '#460000'
  Actual: 'Color(0xff460000)'

@joshmossas
Copy link

joshmossas commented Jul 25, 2024

Ran across this issue and wrote my own helper function to get around it. Thought I'd share here in case anyone else found it useful.

String colorToHexCode(Color color, {ignoreTransparency = false}) {
  // takes in a number from 0-255 and converts it to the equivalent Hex value
  String rgbValueToHexValue(int num) {
    assert(num <= 255 && num >= 0);
    if (num == 0) {
      return "00";
    }
    const hexChars = "0123456789ABCDEF";
    final val = (num / 16);
    final firstVal = val.floor().toInt();
    final secondVal = (val.remainder(firstVal) * 16).toInt();
    return "${hexChars[firstVal]}${hexChars[secondVal]}";
  }

  var result =
      "#${rgbValueToHexValue(color.red)}${rgbValueToHexValue(color.green)}${rgbValueToHexValue(color.blue)}";
  if (color.opacity < 1.0 && !ignoreTransparency) {
    final numVal = (255 * color.opacity).round();
    result += rgbValueToHexValue(numVal);
    return result;
  }
  return result;
}

@joshmossas
Copy link

@ggichure

I'm willing to open a PR to add a fix for this if you'd like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants