我有一个动态变量,该变量将以某些颜色初始化
String bgColor = "#f8d547";
我想通过该变量设置此color属性
decoration: BoxDecoration(
color: bgColor,
),
我该如何实现? 谢谢。
答案 0 :(得分:1)
color:Color(int.parse(bgColor.replaceAll('#','0x')));
答案 1 :(得分:0)
与How do I use hexadecimal color strings in Flutter?重复
请去那里获得详细的答案,无论如何,这是您想要的。
您必须创建一个新功能,可以将其创建为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')}';
}
要使用它:
final Color color = HexColor.fromHex('#aabbcc');