skip to Main Content

I have color value Color(0XFFDDDDDD) stored as a string in my database. I want it to convert to Color widget in flutter. How can I do it?
Here is image of flutter color value picked from color picker.

I tried spliting the string to remove Color() and to take 0XFFDDDDDD value but it didnt’t worked. I want to be able to use this string value to color value like: Container(color: Color(0XFFDDDDDD))

2

Answers


  1. This should work:

    String s = "0xffdddddd";
    Container(color: Color(int.parse(s)))
    
    Login or Signup to reply.
  2. This will give you the Hex colour string

     String color = "Color(0XFFDDDDDD)";
     String hex = color.substring(0, color.length - 1);
     hex = hex.substring(6, hex.length);
    

    Parse it to a color: Color(int.parse(hex));

    Ideally, your hex colour should also be saved as a pure hex colour in the DB so that you do not have to format the string unnecessarily.

    Btw if the parsing doesn’t work try this extension:

    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')}';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search