如何将Flutter颜色转换为字符串并转换回颜色 [英] How to convert Flutter color to string and back to a color

查看:716
本文介绍了如何将Flutter颜色转换为字符串并转换回颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将颜色转换为字符串。然后,我将颜色转换为字符串。不幸的是,当我要将其转换为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;

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

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

推荐答案

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

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

现在,在您提供的示例中, toString 实际上只是创建当前 Color 值的字符串表示形式。并且由于该对象是字符串,因此您无法将其更改为颜色颜色。相反,您可以将String解析为一个值并构造一个新的 Color 对象。

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);

这篇关于如何将Flutter颜色转换为字符串并转换回颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆