Search code examples
dartparsingcolorshex

How to parse 6-digit hexadecimal integer from String in dart?


I can't find a way to parse a string like '0xFFBBD1F0' to the integer 0xFFBBD1F0. Actually I just need to create a Color having only '0xFFBBD1F0' string.

I needed to create a Color from String I got from the server that looks like 'FFFFFF'. The Colors are usually created like Color(0xFFFFFFFF). So I wrote a code to add '0xFF' to the part I got from server and used int.parse method. Than I tried another combinations of this method, with radix argument and without, I tried somehow change the String I pass to int.parse, but nothing worked. While trying I only got a number, for example, 4290499056 or a FormatException.

The code example:

void main() {
  String data = '0xFFBBD1F0';
  var cl = int.parse(data, radix: 16);
  print(cl);
}

Believe the code above should work correctly, but I get this: Uncaught Error: FormatException: 0xFFBBD1F0

Changing code to:

void main() {
  String data = '0xFFBBD1F0';
  var cl = int.parse(data);
  print(cl);
}

only leads me to the output value: 4290499056 when I want to get 0xFFBBD1F0.

So is that possible in dart to convert the String '0xFFBBD1F0' to the int 0xFFBBD1F0? And if it is, than how? If it is not, is there a way to create a color having only 'BBD1F0' String as an input?


Solution

  • This is a very complex and non-trivial task.
    Try this code.

    void main() {
      String data = '0xFFBBD1F0';
      // So is that possible in dart to convert the String '0xFFBBD1F0' to the int 0xFFBBD1F0?
      // And...
      // ...convert the String '0xFFBBD1F0' to the int 0xFFBBD1F0
      var cl = int.parse(data);
      print(cl);
      // Yes!!! It works!
      print(cl == 0xFFBBD1F0);
      print('0x${cl.toRadixString(16).toUpperCase()}');
    }
    

    Output:

    4290499056
    true
    0xFFBBD1F0