Flutter/Dart: Convert HEX color string to Color?

前端 未结 5 836
醉酒成梦
醉酒成梦 2020-12-10 02:24

Our database has colors saved as a String like \"#AABBCC\" and so I\'m basically looking for a function like this: Color.parseColor(\"#AABBCC\"); f

5条回答
  •  再見小時候
    2020-12-10 03:15

    I'm using this function in my project which handles converting the hex string to a Color.

    Color hexToColor(String hexString, {String alphaChannel = 'FF'}) {
      return Color(int.parse(hexString.replaceFirst('#', '0x$alphaChannel')));
    }
    

    The idea here is that now you can pass this function a hex string which is something like this '#ffffff' in addition to that you can pass an alpha channel. What alpha channel does is it handles the opacity of your color and you can pass it to Color directly.

    About alpha channels the FF part is a hex representation of 0-100 is like:

    0 = 00 1 = 03 2 = 05 ... 9 = 17 ... 10 = 1A 11 = 1C 12 = 1F ... 99 = FC 100 = FF

    Let's assume you want to convert #000000 into a Color and have a 0.1 opacity on it. You can simply call this function like this:

    hexToColor('#000000', alphaChannel: '1A');
    

    And if you just call it like this:

    hexToColor('#000000');
    

    Then it will only return you a black color with 1 opacity. Hope this will help to anyone wondering how to handle opacity and color handling a bit more further.

提交回复
热议问题