如何将像#b74093
这样的十六进制颜色字符串转换为Flutter中的Color
?
还有另一种解决方案。如果将颜色存储为普通十六进制字符串并且不想为其添加不透明度(前导FF):1)将十六进制字符串转换为int要将十六进制字符串转换为整数,请执行以下操作之一:
var myInt = int.parse(hexString, radix: 16);
要么
var myInt = int.parse("0x$hexString");
作为0x(或-0x)的前缀将使int.parse默认为16的基数。
2)通过代码为您的颜色添加不透明度
Color color = new Color(myInt).withOpacity(1.0);
如果您的颜色是#e41749,请在它之前添加0xff
所以你可以把它写成:
颜色:颜色(0xffe41749);
"#b74093"
?好...
int getColorHexFromStr(String colorStr)
{
colorStr = "FF" + colorStr;
colorStr = colorStr.replaceAll("#", "");
int val = 0;
int len = colorStr.length;
for (int i = 0; i < len; i++) {
int hexDigit = colorStr.codeUnitAt(i);
if (hexDigit >= 48 && hexDigit <= 57) {
val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 65 && hexDigit <= 70) {
// A..F
val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 97 && hexDigit <= 102) {
// a..f
val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
} else {
throw new FormatException("An error occurred when converting a color");
}
}
return val;
}
import 'package:flutter/material.dart';
class HexToColor extends Color{
static _hexToColor(String code) {
return int.parse(code.substring(1, 7), radix: 16) + 0xFF000000;
}
HexToColor(final String code) : super(_hexToColor(code));
}
导入新类并像使用HexToColor('#F2A03D')
一样使用它
const appBackground = Color(0xffdf7599);
df7599
是你颜色的十六进制代码
您可以单击Color Widget,它会更深入地告诉您这些字母代表的含义。您还可以使用Color.fromARGB()方法创建自定义颜色,这对我来说更容易。使用Flutter Doctor Color Picker网站为您的颤动应用程序挑选任何颜色。