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

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

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

在Flutter中,

Color
该类仅接受 整数
作为参数,或者可以使用命名的构造函数
fromARGB
fromRGBO

因此,我们只需要将字符串转换为

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

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

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

const color = const Color(0xFFB74093);

从Dart开始

2.6.0
,您可以
extension
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
也可以在
mixin
或中声明该方法,
class
因为
HexColor
要使用该名称需要显式指定名称,但是该扩展名对该
toHex
方法很有用,可以隐式使用。这是一个例子:

void main() {  final Color color = HexColor.fromHex('#aabbcc');  print(color.toHex());  print(const Color(0xffaabbcc).toHex());}
使用十六进制字符串的缺点

这里的许多其他答案都显示了如何

Color
像上面我一样从十六进制字符串动态创建a 。但是,这样做意味着颜色不能为
const

理想情况下,您将按照我在此答案第一部分中说明的方式分配颜色,这在大量实例化颜色时效率更高(通常是Flutter小部件)。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4914015.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存