-1

Im trying to convert a hex color to a const Color to be used in MaterialColor. Im not sure how to setup the factory, so the class can return a const Color. My class:

class HtmlColor extends Color {

  factory HtmlColor(String hexCode, int amt) {
    if (hexCode[0] == "#") {
      hexCode = hexCode.substring(1, 7);
    }
    var num = int.parse(hexCode, radix: 16);
    var r = (num >> 16) + amt;
    if (r > 255) r = 255;
    else if  (r < 0) r = 0;
    var b = ((num >> 8) & 0x00FF) + amt;
    if (b > 255) b = 255;
    else if  (b < 0) b = 0;
    var g = (num & 0x0000FF) + amt;
    if (g > 255) g = 255;
    else if (g < 0) g = 0;
    return new HtmlColor.fromValue((g | (b << 8) | (r << 16)) + 0xFF000000);
  }

  const HtmlColor.fromValue(int value) : super(value);

}
Mythar
  • 479
  • 1
  • 5
  • 10
  • Possible duplicate of [Flutter/Dart: Convert HEX color string to Color?](https://stackoverflow.com/questions/50381968/flutter-dart-convert-hex-color-string-to-color) – Luke May 19 '18 at 16:04

2 Answers2

0
String colorString = "0xFF42A5F5";
String valueString = colorString.split('0x')[1]; 
int value = int.parse(valueString, radix: 16);
Color color = new Color(value);

copied from this answer How to convert Flutter color to string and back to a color

Tree
  • 29,135
  • 24
  • 78
  • 98
  • No, it dose not work when assign a Color to the MaterialColor. It has to be a Const. ex: 500: const Color(0xFF000000) - works; 500: const Color(someFunction()) - dose not work. – Mythar May 20 '18 at 06:42
0

There is a utils package that contains a ColorUtils class that can convert hex to int and int to hex. That can be used to create the Flutter colors.

Github: https://github.com/Ephenodrom/Dart-Basic-Utils

PuDev: https://pub.dev/packages/basic_utils

Install :

basic_utils: ^2.0.0

Example :

Color color = Color(ColorUtils.hexToInt("#FFFFFF"));
String hex = ColorUtils.intToHex(color.value);
Ephenodrom
  • 1,797
  • 2
  • 16
  • 28