【问题标题】:Flutter - Using Custom Hex colours [duplicate]Flutter - 使用自定义十六进制颜色
【发布时间】:2019-04-19 03:16:12
【问题描述】:

如何在 Flutter 中添加十六进制值的颜色?例如,我正在尝试以下操作:

Widget build(BuildContext context) {
  return Row(
    children: <Widget>[
      Expanded(
        child: Container(
          padding: EdgeInsets.only(left: 20.0),
          height: 100.0,
          decoration: BoxDecoration(
            color: Color.hex("#183451"),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Image.asset('assets/main_image.png'),
              // More widgets here
            ],
          ),
        ),
      ),
    ],
  );
}

但是得到以下错误:

错误:参数类型 'color::Color' 不能分配给 参数类型 'dart.ui::Color

这是使用“颜色”包: https://pub.dartlang.org/packages/color

如果我使用MaterialColor,它将按预期工作:

color: Colors.blue

我想我需要创建一个MaterialColor,但是这些需要一个整数值和样本。十六进制值是否需要从字符串转换为整数?如果可能的话,我想寻找一些如何实现这一点的代码示例:)

提前致谢

【问题讨论】:

    标签: dart flutter


    【解决方案1】:
    Color parseColor(String color) {
      String hex = color.replaceAll("#", "");
      if (hex.isEmpty) hex = "ffffff";
      if (hex.length == 3) {
        hex =
            '${hex.substring(0, 1)}${hex.substring(0, 1)}${hex.substring(1, 2)}${hex.substring(1, 2)}${hex.substring(2, 3)}${hex.substring(2, 3)}';
      }
      Color col = Color(int.parse(hex, radix: 16)).withOpacity(1.0);
      return col;
    }
    

    【讨论】:

      【解决方案2】:

      您实际上不需要外部包来使用自定义颜色。

      Color(0xFF183451)这样使用它,其中FF是透明度,00是透明的,FF是不透明的。

      【讨论】:

      • 有没有办法使用这些颜色的 50% 或任何 %?像颜色(0xFF183451)[50]?
      猜你喜欢
      • 1970-01-01
      • 2019-06-16
      • 2021-03-08
      • 1970-01-01
      • 2011-10-25
      • 2019-10-29
      • 2018-10-09
      • 2020-03-05
      相关资源
      最近更新 更多