【问题标题】:Flutter cant show string color code in colorFlutter无法以颜色显示字符串颜色代码
【发布时间】:2021-01-12 10:54:46
【问题描述】:

我需要显示容器中的颜色。意思是我有字符串格式的颜色代码,我需要用作容器颜色。

                  decoration: BoxDecoration(
                  color: widget.product.colors[i].toColor(),
                  borderRadius: BorderRadius.all(Radius.circular(40)),

这是我正在做的简单代码,但显示错误

Invalid argument(s): Can not interpret string 0xFFF6625E

如果我删除 .toColor() 那么它的显示

Error: The argument type 'String' can't be assigned to the parameter type 'Color'.

谁能告诉我如何显示这个?

【问题讨论】:

标签: flutter


【解决方案1】:

您可以使用以下代码:

  decoration: BoxDecoration(
    //make sure that the widget.product.colors[i] is a hex code (i.e: "0xff0000")
     color : Color(int.parse(widget.product.colors[i])),
     borderRadius: BorderRadius.all(Radius.circular(40)),
     border: Border.all(color: Color(int.parse(kPrimaryColor)))

【讨论】:

    【解决方案2】:

    你可以写一个这样的方法..

    static Color hexToColor(String code) {
        if(code.length == 6) {
          return Color(int.parse(code.substring(0, 6), radix: 16) + 0xFF000000);
        }
        else {
          return Color(int.parse(code.substring(0, 8), radix: 16) + 0x00000000);
        }
      }
    

    【讨论】:

      【解决方案3】:

      您可以使用Supercharged 包:

      "#ff00ff".toColor(); // painless hex to color
      "red".toColor(); // supports all web color names
      

      【讨论】:

        【解决方案4】:

        你可以试试这个:

        color: const Color(widget.product.colors[i]),
        

        【讨论】:

          猜你喜欢
          • 2021-07-23
          • 2019-07-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-23
          • 1970-01-01
          • 2014-09-27
          • 2023-03-17
          相关资源
          最近更新 更多