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

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

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

回答:

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小部件)。

以上是 如何在Flutter中使用十六进制颜色字符串? 的全部内容, 来源链接: utcz.com/qa/426106.html

回到顶部