天天看點

flutter 中如何使用hex設定顔色

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