我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
当前回答
最好的方法是使用来自pub.dev的flutter十六进制颜色插件 然后导入包。
import 'package:hexcolor/hexcolor.dart';
然后把它用在这种特殊的方式上。
Text(
'Running on: $_platformVersion\n',
style: TextStyle(color: HexColor("#f2f2f2")),
),
Text(
"Hex From Material $textColor",
style: TextStyle(color: ColorToHex(Colors.teal)),
),
这里的特殊插件。
其他回答
最简单的方法是将其转换为整数。例如,#BCE6EB。你会添加0xFF,然后你会删除标签,使它:
0 xffbce6eb
然后让我们假设你要通过这样做来实现它:
写成backgroundColor:颜色(0 xffbce6eb)
如果你只能使用十六进制,那么我建议使用Hexcolor包。
简单的方法:
String color = yourHexColor.replaceAll('#', '0xff');
用法:
Container(
color: Color(int.parse(color)),
)
你可以用这个
Color getColorFromColorCode(String code){
return Color(int.parse(code.substring(1, 7), radix: 16) + 0xFF000000);
}
要将十六进制字符串转换为整数,请执行以下操作:
int hexToInt(String hex)
{
int val = 0;
int len = hex.length;
for (int i = 0; i < len; i++) {
int hexDigit = hex.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("Invalid hexadecimal value");
}
}
return val;
}
电话的例子:
Color color = new Color(hexToInt("FFB74093"));
在文件中添加此函数
Color parseColor(String color) {
String hex = color.replaceAll("#", "");
if (hex.isEmpty) hex = "ffffff";
if (hex.length == 3) {
hex = '${hex.substring(0, 1)}${hex.substring(0, 1)}${hex.substring(1, 2)}${hex.substring(1, 2)}${hex.substring(2, 3)}${hex.substring(2, 3)}';
}
Color col = Color(int.parse(hex, radix: 16)).withOpacity(1.0);
return col;
}
然后像-一样使用它
Container(
color: parseColor("#b74093")
)