Flutter中使用十六进制颜色字符串

#b74093为例
在Flutter中,Color类只接受整数作为参数,或者可以使用指定的构造函数fromARGBfromRGBO
我们的目标是将字符串#b74093转换为整数值,同时需要指定不透明度(一般不透明度为100%,用十六进制表示即为0xFF)。接下来只需要将颜色值添加上去就行了,如下

const color = const Color(0xffb74093); // Second `const` is optional in assignments.

从Dart 2.6.0开始,您可以为Color类创建一个扩展,该扩展允许您使用十六进制颜色字符串来创建一个Color对象。

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')}';
}

fromHex方法也可以在mixinclass中声明,因为需要显式地指定HexColor才能使用它,但是扩展对于toHex方法很有用,它可以隐式地使用。这是一个例子

void main() {
  final Color color = HexColor.fromHex('#aabbcc');

  print(color.toHex());
  print(const Color(0xffaabbcc).toHex());
}
发布了69 篇原创文章 · 获赞 189 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_36721220/article/details/104984441