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

查看:120
本文介绍了如何将 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 中,as 操作符不允许你改变对象的实际结构,它只允许你提供一个暗示一个对象可能有一个更具体的类型.例如,如果您有一只狗和一个动物类,您可以使用 as 来指定您的动物实际上是一只狗(只要对象 实际上是一只狗).

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 值的字符串表示.因为这个对象是一个字符串,你不能用 as 把它改回 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天全站免登陆