flutter开发中,要设置颜色,其提供的Color只能够使用16进制,但UI提供给我们的一般是hex字符串,为了方便的使用hex,我们需要自己封装相关的转换方法。以下代码是参考stackoverflow的回答改造而来。
class ColorUtil {
/// 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));
}
}
使用
ColorUtil.fromHex('#F96600')
参考:https://stackoverflow.com/questions/50081213/how-do-i-use-hexadecimal-color-strings-in-flutter