Home > Enterprise >  How to convert a hex color in flutter they way I did in swift?
How to convert a hex color in flutter they way I did in swift?

Time:09-29

This is the code worked in swift. How to do the same in flutter? I am new to flutter. How can I convert this code to flutter?

hexcolor='#4D0000FF';

extension UIColor {

public convenience init?(hex: String) {
 let r, g, b, a: CGFloat
    if hex.hasPrefix("#") {

        let start = hex.index(hex.startIndex, offsetBy: 1)
        let hexColor = String(hex[start...])
        if hexColor.count == 8 {
            let scanner = Scanner(string: hexColor)
            var hexNumber: UInt64 = 0

            if scanner.scanHexInt64(&hexNumber) {
                r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                a = CGFloat(hexNumber & 0x000000ff) / 255
                self.init(red: r, green: g, blue: b, alpha: a)
                return
            }
        }
    }

    return nil
}}

CodePudding user response:

to convert Hex string to color in flutter: try this

hexStringToColor(String hexColor) {
  hexColor = hexColor.toUpperCase().replaceAll("#", "");
  if (hexColor.length == 6) {
    hexColor = "FF"   hexColor;
  }
  return Color(int.parse(hexColor, radix: 16));
}

on your widget for example:

Text("Hello World",
    style:TextStyle(
     color: hexStringToColor(hexCode)
  ));

CodePudding user response:

Here's how you can do it:

extension HexColor on Color {
  /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
  static Color fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
  String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${alpha.toRadixString(16).padLeft(2, '0')}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}';
}

CodePudding user response:

You can achieve as follows:

 class HexColor extends Color {
  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF"   hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }

  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));
}

And then call HexColor as:

  static Color buttonBlack = HexColor("#1C1C1C");
  • Related