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

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

   Color newColor;

   newColor = testingColorString as Color;

类型'String'不是类型转换中'Color'类型的子类型,其中
字符串来自dart:core
颜色来自dart:ui

最佳答案

在Dart中,as运算符不允许您更改对象的实际结构,而只是允许您提供提示,表明对象可能具有更特定的类型。例如,如果您有一只狗和一个动物类,则可以使用来指定您的动物实际上是狗(只要对象实际上是狗)。

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

现在,在示例中,您提供的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);

07-25 22:14
查看更多