以#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 `tru