Home > Software engineering >  How to convert string to color in Flutter
How to convert string to color in Flutter

Time:11-02

I want to convert the string to color but I can't,

My Code

String color = "0xffff5252";
Color result= Color(int.parse(color, radix: 16));
print("$result");

** I get the following problem**

Invalid radix-16 number (at character 1) 0xffff5252

CodePudding user response:

You can try something like below

String color = "0xffff5252";
Color result= Color(int.parse(color));
print(result);

CodePudding user response:

if youe motive is to define a color by first defining into string and then by parsing it, then there's a much simpler way to define color,

    const Color primary = Color(0xFF92A3FD);
const Color secondary = Color(0xFF9DCEFF);
const Color thirdColor = Color(0xFFC58BF2);
const Color fourthColor = Color(0xFFEEA4CE);
const Color bgTextField = Color(0xFFF7F8F8);

const Color facebookColor = Color(0xFF3b5998);
const Color googleColor = Color(0xFFDB4437);

CodePudding user response:

Try this hexToColor function:

 // Construct a color from a hex code string, of the format RRGGBB.
 Color hexToColor(String code) {
 return Color(int.parse(code.substring(1, 6), radix: 16)   0xFF000000);
 }

This worked for me to store a color & use it as a profile avatar color.

  • Related