【发布时间】:2021-01-25 21:15:20
【问题描述】:
我有一个动态变量,它将由一些颜色启动
String bgColor = "#f8d547";
我想从那个变量中设置这个颜色属性
decoration: BoxDecoration(
color: bgColor,
),
我怎样才能做到这一点? 谢谢。
【问题讨论】:
我有一个动态变量,它将由一些颜色启动
String bgColor = "#f8d547";
我想从那个变量中设置这个颜色属性
decoration: BoxDecoration(
color: bgColor,
),
我怎样才能做到这一点? 谢谢。
【问题讨论】:
颜色: 颜色(int.parse(bgColor.replaceAll('#', '0x')));
【讨论】:
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');
【讨论】: