Flutter 16进制数字符串转 int

7,283 阅读1分钟

Flutter 中 Color 接收 int 型十六进制数,如果颜色数据是从后台获取,则一般拿到字符串,此时需要转为 int

Flutter 中 Color 定义:

(new) Color(int value) → Color
dart.ui

Construct a color from the lower 32 bits of an [int].

The bits are interpreted as follows:

Bits 24-31 are the alpha value.
Bits 16-23 are the red value.
Bits 8-15 are the green value.
Bits 0-7 are the blue value.
In other words, if AA is the alpha value in hex, RR the red value in hex, GG the green value in hex, and BB the blue value in hex, a color can be expressed as const Color(0xAARRGGBB).

For example, to get a fully opaque orange, you would use const Color(0xFFFF9000) (FF for the alpha, FF for the red, 90 for the green, and 00 for the blue).

第一种方法 16进制数字符串转 int

int _hexToInt(String hex) {
  int val = 0;
  int len = hex.length;
  for (int i = 0; i < len; i++) {
    int hexDigit = hex.codeUnitAt(i);
    if (hexDigit >= 48 && hexDigit <= 57) {
      val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
    } else if (hexDigit >= 65 && hexDigit <= 70) {
      // A..F
      val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
    } else if (hexDigit >= 97 && hexDigit <= 102) {
      // a..f
      val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
    } else {
      throw new FormatException("Invalid hexadecimal value");
    }
  }
  return val;
}

第二种方法

如果后台返回的字符串中包含 '#', '0x' 前缀, 或者包含透明度,可处理一下

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

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