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

前端 未结 4 1632
小蘑菇
小蘑菇 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:06

    Leveraging the power of Dart extensions we can augment String with a function that returns a Color:

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

    Set a string color code value in the color property.

     child: Text("Text Color",
                 style: TextStyle(
                 color: '#55B9F4'.toColor(),
                  ),
                 )
    

提交回复
热议问题