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.

3 Answers 3

3

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(),
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks so much and it really worked. Do you have any idea to do the same with "TextAlign.left"
@YashMakan I am also curious for the solution for that, And trying to find a perfect solution for that too.
Hey @YashMakan I have found the workaround for the textAlign too, You Can check my updated solution.
You saved me hours of coding....
1

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

Color myColor = Color(0xff123456);

and use this color later.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.