Chrystian
Chrystian

Reputation: 1047

How to convert Flutter color to string and back to a color

I am converting a Color to a String. I am then converting the Color to a String. Unfortunately when I want to convert it back into a Color the operation fails:

   Color pickerColor = new Color(0xff443a49);
    String testingColorString = pickerColor.toString();

   Color newColor;

   newColor = testingColorString as Color;

type 'String' is not a subtype of type 'Color' in type cast where String is from dart:core Color is from dart:ui

Upvotes: 30

Views: 49561

Answers (9)

Herpi Tekstil
Herpi Tekstil

Reputation: 1

If you have a limited list of colors, you can create a function like so:

Color colorFromString(String colorString){
  Color resultColor;
  switch (colorString) {
    case 'blue':
      resultColor = Colors.blue;
      break;
    case 'green':
      resultColor = Colors.green;
      break;
    default:
      resultColor = Colors.teal;
  }
  return resultColor;
}

Usage:

Color newColor = colorFromString('blue');

For converting hex color to Color format, you can do so by parsing hex RGB, converting them to decimal and use Color.fromARGB to create the output Color format:

Color hexStringToColor(String hexString) {
  if (hexString.startsWith('0x')) {//removes the prceding 0x since we dont need it.
    hexString = hexString.substring(2);
  }

  // Is the string is 6 characters long, add ff for alpha, but further validation is needed
  if (hexString.length == 6) {
    hexString = 'ff$hexString';
  }

  int hexValue = int.parse(hexString, radix: 16);//radix 16 means hexadecimal
  int alpha = (hexValue >> 24) & 0xFF;// The sign >> is bitwise shift to right operator
  int red = (hexValue >> 16) & 0xFF;
  int green = (hexValue >> 8) & 0xFF;
  int blue = hexValue & 0xFF;

  return Color.fromARGB(alpha, red, green, blue);
}

Usage:

Color newColor = hexStringToColor('0xff443a49');

Upvotes: 0

Bobin
Bobin

Reputation: 435

If using JsonSerialize, you can use this:

class ColorConverter implements JsonConverter<Color, int> {
  const ColorConverter();
  @override Color fromJson(int json) => Color(json);
  @override int toJson(Color object) => object.value;
}

Then annote your color field ike this:

@JsonSerializable()
class MyClass {
  @ColorConverter Color myColor;
}

Very convenient.

Upvotes: 2

mohammad mowludi
mohammad mowludi

Reputation: 21

use this site to convert hex color to rgb color and set folow code

https://www.w3schools.com/colors/colors_hexadecimal.asp

backgroundColor: const Color.fromRGBO(212, 23,79, 0.99),

Upvotes: -1

Thiago Silva
Thiago Silva

Reputation: 796

Add this two functions

int convertToInt(Color color) {
return color.value;
}



Color convertToColor(int intColor) {
return Color(intColor);
}

then you can just

int intcolor = ColorUtils().convertToInt(Colors.amber); //convert the color to int
print(intcolor.toString()); //se it
Color mycolor = ColorUtils().convertToColor(intcolor); //retrieve the color

Now if you really want to store it as String, just do:

intcolor.toString();

and when retrieve it from firestore

Color mycolor = ColorUtils().convertToColor(int.Parse(retrievedStrColor));

Upvotes: 0

MOE
MOE

Reputation: 51

Another easy way to save color in firebase and retrieve is to first to save the value of the color as String and store this value in firebase like this.

Color black = Colors.black; // example black color

String _storeColorValue = black.value.toString() ;

This is will give 4278190080 as the black color value. you store this value as String to firebase.
You can retrieve color value and change it back to color like this :

int value = int.parse(_storeColorValue);

Color color = Color(value).withOpacity(1); 

This is will give us back the color with help of the color value and withOpacity(1) which returns a new color that matches the value we passed in.

Upvotes: 4

Amit Sachan
Amit Sachan

Reputation: 91

Use the following code to get hex value of the color.

Color color = Colors.red;
var hexCode = '#${color.value.toRadixString(16).substring(2, 8)}';

Upvotes: 7

Mr Bhati
Mr Bhati

Reputation: 789

Leveraging the power of Dart extensions we can augment String with a function that returns a Color:

extension ColorExtension on String {
  toColor() {
    var hexColor = this.replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    if (hexColor.length == 8) {
      return Color(int.parse("0x$hexColor"));
    }
  }
}

Set a string color code value in the color property.

 child: Text("Text Color",
             style: TextStyle(
             color: '#55B9F4'.toColor(),
              ),
             )

Upvotes: 40

Jonah Williams
Jonah Williams

Reputation: 21421

In Dart the as operator doesn't allow you to change the actual structure of an Object, it just allows you to provide a hint that an object might have a more specific type. For example, if you had a dog and an animal class you could use as to specify that your animal is actually a dog (as long as the object is actually a dog).

class Animal {}
class Dog extends Animal {}

Animal animal = new Dog();
Dog bob = animal as Dog; // works, since animal is actually a dog
Animal animal2 = new Animal();
Dog bob2 = animal2 as Dog; // fails, since animal2 is actually an Animal

Now, in the example you've provided toString actually just creates a String representation of the current Color value. And since this object is a String, you can't change it back to a Color with an as. Instead, you can parse the String into a value and construct a new Color object.

Color color = new Color(0x12345678);
String colorString = color.toString(); // Color(0x12345678)
String valueString = colorString.split('(0x')[1].split(')')[0]; // kind of hacky..
int value = int.parse(valueString, radix: 16);
Color otherColor = new Color(value);

Upvotes: 52

icazevedo
icazevedo

Reputation: 612

You actually can't do that. Color doesn't have a constructor that accepts a String as a representation of a color.

For that, you could use the Color property value. It is a 32 bit int value that represents your color. You can save it and then use to create your new Color object.

The code could look like this

Color pickerColor = new Color(0xff443a49);
int testingColorValue = pickerColor.value;
String testingColorString = pickerColor.toString();

Color newColor = new Color(testingColorValue);

or like this

Color pickerColor = new Color(0xff443a49);
String testingColorString = pickerColor.toString();

Color newColor = new Color(pickerColor.value);

Upvotes: 42

Related Questions