如何在Flutter中使用十六进制颜色字符串?

问题描述 投票:62回答:9

如何将像#b74093这样的十六进制颜色字符串转换为Flutter中的Color

colors dart flutter
9个回答
9
投票

还有另一种解决方案。如果将颜色存储为普通十六进制字符串并且不想为其添加不透明度(前导FF):1)将十六进制字符串转换为int要将十六进制字符串转换为整数,请执行以下操作之一:

var myInt = int.parse(hexString, radix: 16);

要么

var myInt = int.parse("0x$hexString");

作为0x(或-0x)的前缀将使int.parse默认为16的基数。

2)通过代码为您的颜色添加不透明度

Color color = new Color(myInt).withOpacity(1.0);

8
投票

如果您的颜色是#e41749,请在它之前添加0xff

所以你可以把它写成:

颜色:颜色(0xffe41749);


2
投票

"#b74093"?好...

To HEX Recipe

int getColorHexFromStr(String colorStr)
{
  colorStr = "FF" + colorStr;
  colorStr = colorStr.replaceAll("#", "");
  int val = 0;
  int len = colorStr.length;
  for (int i = 0; i < len; i++) {
    int hexDigit = colorStr.codeUnitAt(i);
    if (hexDigit >= 48 && hexDigit <= 57) {
      val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
    } else if (hexDigit >= 65 && hexDigit <= 70) {
      // A..F
      val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
    } else if (hexDigit >= 97 && hexDigit <= 102) {
      // a..f
      val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
    } else {
      throw new FormatException("An error occurred when converting a color");
    }
  }
  return val;
}

2
投票
import 'package:flutter/material.dart';
class HexToColor extends Color{
  static _hexToColor(String code) {
    return int.parse(code.substring(1, 7), radix: 16) + 0xFF000000;
  }
  HexToColor(final String code) : super(_hexToColor(code));
}

导入新类并像使用HexToColor('#F2A03D')一样使用它


0
投票

const appBackground = Color(0xffdf7599);

df7599是你颜色的十六进制代码


0
投票

您可以单击Color Widget,它会更深入地告诉您这些字母代表的含义。您还可以使用Color.fromARGB()方法创建自定义颜色,这对我来说更容易。使用Flutter Doctor Color Picker网站为您的颤动应用程序挑选任何颜色。

© www.soinside.com 2019 - 2024. All rights reserved.