【问题标题】:How to convert API color code ("#1db8ce") value to Actual RGB color?如何将 API 颜色代码(“#1db8ce”)值转换为实际 RGB 颜色?
【发布时间】:2022-01-08 23:25:26
【问题描述】:

我从 Api 获取所有数据。我想将颜色字符串值转换为实际颜色。我怎样才能做到这一点?

我的 API 响应:

{
"Status": 1,
"Message": "",
"ProductList": [
    {
        "CategoryId": "2",
        "CategoryName": "Women",
        "SubCategoryId": "14",
        "SubCategoryName": "Nighty",
        "DiscountStartDate": "",
        "DiscountEndDate": "",
        "Tag": "Nighty",
       
     
        "ColorList": [
            {
                "ProductId": "52",
                "ProductColor": "#1db8ce"
            },
            {
                "ProductId": "52",
                "ProductColor": "#8ab234"
            }
        ]
    },
   ...................................................

我正在尝试显示这两种颜色,它来自我的 API 在 Row() 中。现在我得到了 2 个红色框(因为我手动设置了红色)。

 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: Colors.red, //I want to use like this ==> colorListListVar.ProductColor
                                                      shape:BoxShape.circle,
                                                    ),
                                                  ),
                                                ),
                                              Spacer(),
                                            ],
                                          ),

【问题讨论】:

    标签: json flutter api dart colors


    【解决方案1】:

    您可以通过这种方式轻松实现:

    String color = '#1db8ce';
    Color actualColor = Color(int.parse(color.replaceAll('#','0xff')));
    

    【讨论】:

    • 完全明白。但我只能通过 colorListListVar.productColor 访问我的 JSON Api 颜色值。 (productColor来自模型)
    • 只需将我示例中的color 变量替换为具有颜色十六进制代码的变量,即Color(int.parse(colorListListVar.productColor.replaceAll('#','0xff')))