微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Flutter中使用十六进制颜色字符串?

如何解决如何在Flutter中使用十六进制颜色字符串?

Flutter中, 仅接受 作为参数,或者可以使用命名的构造函数fromARGBfromRGBO

因此,我们只需要将字符串转换#b74093整数值即可。另外,我们需要尊重始终需要指定 。255(完全)不透明度由十六进制值表示FF。这已经给我们留下了 。现在,我们只需要像这样添加颜色字符串即可:

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

可以选择是否将字母大写:

const color = const Color(0xFFB74093);

从Dart开始2.6.0,您可以extensionColor类创建一个,让您使用十六进制颜色字符串创建一个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也可以在mixin或中声明该方法class因为HexColor要使用该名称需要显式指定名称,但是该扩展名对该toHex方法很有用,可以隐式使用。这是一个例子:

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

  print(color.toHex());
  print(const Color(0xffaabbcc).toHex());
}

使用十六进制字符串的缺点

这里的许多其他答案都显示了如何Color像上面我一样从十六进制字符串动态创建a 。但是,这样做意味着颜色不能为const。 理想情况下,您将按照我在此答案第一部分中说明的方式分配颜色,这在大量实例化颜色时效率更高(通常是Flutter小部件)。

解决方法

如何转换一个 十六进制颜色字符串#b74093 一个Color在颤振?

我想在Dart中使用十六进制颜色代码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。