如何将Flutter颜色转换为字符串并返回颜色

Chr*_*ian 3 dart flutter

我正在将颜色转换为字符串.然后我将Color转换为String.不幸的是,当我想将它转换回Color时,操作失败:

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

   Color newColor;

   newColor = testingColorString as Color;
Run Code Online (Sandbox Code Playgroud)

类型"字符串"不是类型的类型转换的子类型"颜色",其中字符串是由镖:核心颜色是从镖:UI

ica*_*edo 24

你实际上不能这样做。Color 没有接受 String 作为颜色表示的构造函数。

为此,您可以使用 Color 属性。它是一个 32 位int值,代表您的颜色。您可以保存它,然后使用它来创建新的 Color 对象。

代码可能是这样的

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

Color newColor = new Color(testingColorValue);
Run Code Online (Sandbox Code Playgroud)

或者像这样

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

Color newColor = new Color(pickerColor.value);
Run Code Online (Sandbox Code Playgroud)

  • 即使解决方案不使用 String 作为过渡类型,这也应该是一个可接受的答案 (2认同)
  • 它还为我提供了一种使用 json_serialized 保存 Material.color 的方法。所以谢谢你! (2认同)

Jon*_*ams 10

在Dart中,as运算符不允许您更改Object的实际结构,它只允许您提供对象可能具有更具体类型的提示.例如,如果你有一只狗,你可以作为使用动物类,指定你的动物实际上是一个狗(只要对象实际上是狗).

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
Run Code Online (Sandbox Code Playgroud)

现在,在您提供的示例中,toString实际上只创建了当前Color值的String表示.而且,由于这个对象是一个字符串,你不能改变它回Coloras.相反,您可以将String解析为值并构造新Color对象.

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);
Run Code Online (Sandbox Code Playgroud)


小智 7

利用 Dart 扩展的强大功能,我们可以使用返回Color的函数来扩充String

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"));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在颜色属性中设置字符串颜色代码值。

 child: Text("Text Color",
             style: TextStyle(
             color: '#55B9F4'.toColor(),
              ),
             )
Run Code Online (Sandbox Code Playgroud)


小智 5

使用以下代码获取颜色的十六进制值。

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