以#b74093
为例
在Flutter中,Color
类只接受整数作为参数,或者可以使用指定的构造函数fromARGB
和fromRGBO
。
我们的目标是将字符串#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
方法也可以在mixin
或class
中声明,因为需要显式地指定HexColor
才能使用它,但是扩展对于toHex
方法很有用,它可以隐式地使用。这是一个例子
void main() {
final Color color = HexColor.fromHex('#aabbcc');
print(color.toHex());
print(const Color(0xffaabbcc).toHex());
}