You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API返回的十六进制颜色码(如#1db8ce)转换为Flutter可用的RGB颜色?

实现方案

步骤1:实现十六进制颜色转换工具

Flutter内置的Color类仅支持接收32位整数格式的色值,因此你需要先编写转换函数将API返回的#RRGGBB格式字符串转换为可识别的Color实例:

Color hexToColor(String hexString) {
  // 异常兜底:格式错误时返回灰色
  if(hexString.isEmpty || !hexString.startsWith('#')) return Colors.grey;
  final String formattedHex = hexString.replaceFirst('#', '');
  // 6位色值默认补全不透明的alpha通道
  final String alphaHex = formattedHex.length == 6 ? 'FF$formattedHex' : formattedHex;
  return Color(int.parse(alphaHex, radix: 16));
}

步骤2:替换现有代码中的固定色值

把你原有代码中DecoratedBox的color属性从固定的Colors.red替换为调用转换函数即可:

child: Row(
  children: [
    for (var colorListListVar in snapshot.data.productList[index].colorList)
      Container(
        margin: EdgeInsets.only(right: 2),
        padding: EdgeInsets.all(getProportionateScreenWidth(8)),
        height:getProportionateScreenWidth(40),
        width:getProportionateScreenWidth(40),
        decoration: BoxDecoration(
          color: Colors.transparent,
          //border: Border.all(color: kPrimaryColor),
          shape: BoxShape.circle,
        ),
        child: DecoratedBox(
          decoration: BoxDecoration(
            // 替换为转换后的动态色值
            color: hexToColor(colorListListVar.ProductColor),
            shape:BoxShape.circle,
          ),
        ),
      ),
    Spacer(),
  ],
),

可选优化:使用扩展方法简化调用

如果你需要频繁做色值转换,可以给String类型加扩展方法,调用逻辑更简洁:

extension HexColorExtension on String {
  Color toColor() {
    if(isEmpty || !startsWith('#')) return Colors.grey;
    final formatted = replaceFirst('#', '');
    final fullHex = formatted.length == 6 ? 'FF$formatted' : formatted;
    return Color(int.parse(fullHex, radix: 16));
  }
}

调用时直接写:

color: colorListListVar.ProductColor.toColor()

注意事项

  • 转换函数默认兼容#RRGGBB(6位无透明度)和#AARRGGBB(8位带透明度)两种格式的色值字符串
  • 已添加异常兜底逻辑,避免接口返回空值或非法格式时应用崩溃

内容的提问来源于stack exchange,提问作者Toujo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:09:10