1

I have a string as

String stringColor = "Color(0xff000000)";

What I want is to convert stringColor variable to actual Color.
Note:- This is merely an example I also want to convert "TextAlign.left" string to TextAlign.

Any help would be appreciated.

Yash Makan
  • 706
  • 1
  • 5
  • 17

3 Answers3

2

I have found A working solution for Color part, Here is the code

String stringColor = "Color(0xff000000)";
String valueString =
    stringColor.split('(0x')[1].split(')')[0]; // kind of hacky..
print(valueString);
int value = int.parse(valueString, radix: 16);
print(value);
Color otherColor = new Color(value);
print(otherColor);
print(otherColor.runtimeType);

CREDITS

You Can Also use Extension for the same, As Shown HERE

EDITED:

I have made a workaround solution by using Power of Extension, Its working perfectly too.

Add this Outside of Your Class

extension AlignExtensions on String {
  toAlign() {
    if (this.contains("left")) {
      return TextAlign.left;
    } else if (this.contains("center")) {
      return TextAlign.center;
    } else if (this.contains("right")) {
      return TextAlign.right;
    } else if (this.contains("end")) {
      return TextAlign.end;
    }
  }
}

And to use this Extension Class, Use this line of code,

textAlign: "TextAlign.right".toAlign(),
Mukul
  • 1,020
  • 6
  • 12
  • Thanks so much and it really worked. Do you have any idea to do the same with `"TextAlign.left"` – Yash Makan Dec 31 '20 at 06:18
  • @YashMakan I am also curious for the solution for that, And trying to find a perfect solution for that too. – Mukul Dec 31 '20 at 06:19
  • Hey @YashMakan I have found the workaround for the textAlign too, You Can check my updated solution. – Mukul Dec 31 '20 at 06:29
1

You can simply store the color in a variable type of Color

Color myColor = Color(0xff123456);

and use this color later.

S.I.Ayonto
  • 52
  • 8
0

Just use sr.replaceAll.('"', '\"') if is it String variable .Otherwish you can use Color(0xffFFFFFF)

Hasib Akon
  • 580
  • 6
  • 16