问题描述
如何在 Flutter 中将十六进制颜色字符串(如#b74093
)转换为Color
?>
我想在 Dart 中使用十六进制颜色代码.
在 Flutter 中,Color
类 只接受整数作为参数,或者有可能使用命名构造函数 fromARGB
和 fromRGBO
.
所以我们只需要将字符串 #b74093
转换为整数值.此外,我们需要尊重 opacity 始终需要指定.255
(完全)不透明度由十六进制值 FF
表示.这已经给我们留下了 0xFF
.现在,我们只需要像这样附加我们的颜色字符串:
const color = const Color(0xffb74093);//第二个 `const` 在赋值中是可选的.
字母可以选择大写或不大写:
const color = const Color(0xFFB74093);
如果您想使用百分比不透明度值,您可以将第一个 FF
替换为来自 此表(也适用于其他颜色通道).
扩展类
从 Dart 2.6.0
开始,您可以创建一个 扩展
用于 Color
类,它允许您使用十六进制颜色字符串来创建 Color
对象:
扩展 HexColor on Color {///字符串的格式为aabbcc";或ffaabbcc"带有可选的前导#".静态颜色来自十六进制(字符串十六进制字符串){最终缓冲区 = StringBuffer();if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');buffer.write(hexString.replaceFirst('#', ''));返回颜色(int.parse(buffer.toString(),基数:16));}///如果 [leadingHashSign] 设置为 `true`(默认为 `true`),则为哈希符号添加前缀.String toHex({boolleadingHashSign = 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() {最终颜色 color = HexColor.fromHex('#aabbcc');打印(颜色.toHex());打印(常量颜色(0xffaabbcc).toHex());}
使用十六进制字符串的缺点
这里的许多其他答案展示了如何从十六进制字符串动态创建 Color
,就像我在上面所做的那样.但是,这样做意味着颜色不能是 const
.
理想情况下,您可以按照我在本答案第一部分中解释的方式分配颜色,这在大量实例化颜色时效率更高,通常 Flutter 小部件就是这种情况.
How do I convert a hexadecimal color string like #b74093
to a Color
in Flutter?
I want to use a HEX color code in Dart.
In Flutter, the Color
class only accepts integers as parameters, or there is the possibility to use the named constructors fromARGB
and fromRGBO
.
So we only need to convert the string #b74093
to an integer value. Also we need to respect that opacity always needs to be specified.255
(full) opacity is represented by the hexadecimal value FF
. This already leaves us with 0xFF
. Now, we just need to append our color string like this:
const color = const Color(0xffb74093); // Second `const` is optional in assignments.
The letters can by choice be capitalized or not:
const color = const Color(0xFFB74093);
If you want to use percentage opacity values, you can replace the first FF
with the values from this table (also works for the other color channels).
Extension class
Starting with Dart 2.6.0
, you can create an extension
for the Color
class that lets you use hexadecimal color strings to create a Color
object:
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')}';
}
The fromHex
method could also be declared in a mixin
or class
because the HexColor
name needs to be explicitly specified in order to use it, but the extension is useful for the toHex
method, which can be used implicitly. Here is an example:
void main() {
final Color color = HexColor.fromHex('#aabbcc');
print(color.toHex());
print(const Color(0xffaabbcc).toHex());
}
Disadvantage of using hex strings
Many of the other answers here show how you can dynamically create a Color
from a hex string, like I did above. However, doing this means that the color cannot be a const
.
Ideally, you would assign your colors the way I explained in the first part of this answer, which is more efficient when instantiating colors a lot, which is usually the case for Flutter widgets.
这篇关于如何在 Flutter 中使用十六进制颜色字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!