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

前端 未结 4 1625
小蘑菇
小蘑菇 2020-12-06 02:23

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:

<         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-06 03:00

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

提交回复
热议问题